Mapping a list item to a day of the week

Hello friends!

I’m currently trying to write my first timesaving application. Exciting times. I’ve been working through the C# course here on Code Academy. I’ve made a lot of progress, and I feel like I have come a long way in my #100daysofcode

The idea of my application is to add a meal to each day of the week. The idea is that I run the program; it allocates a meal from a list and assigns it to Monday, Tuesday, Wednesday, etc. Here is my code so far. I feel like I will need to use a LINQ query against the list elements to randomise it. I can’t determine the best way to randomise against my days of the week array. Currently, my code works and is very, very fragile.

using System.Collections.Generic;
using WeeklyMealSelector;

string[] dayOfTheWeek = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" };
int tempCounter = 0;

List<Meals> menu = new List<Meals>();
menu.Add(new Meals(1, "Pizza"));
menu.Add(new Meals(2, "Chow mein"));
menu.Add(new Meals(3, "Salad"));
menu.Add(new Meals(4, "Burgers and fries"));
menu.Add(new Meals(5, "Fish and chips"));
menu.Add(new Meals(6, "Chicken and Rice"));
menu.Add(new Meals(7, "Spag Bol"));

var random = new Random();
var randomized = menu.OrderBy(item => random.Next(0, 7));

foreach (var value in randomized)
    Console.WriteLine(dayOfTheWeek[tempCounter] + ": " + value);

Am I approaching this problem in the right way? Am I traversing the wrong path?

Many thanks.

I would like to refer you to this tutorial on Generic and generic data collection which you may find helpful C# Generics: Introduction to Generic Collections in Lesson 20 - C# Station

and Fisher-yate shuffle for random generator
an example would be something like this:

using System; using System.Collections.Generic; public static class Shuffler { private static Random rng = new Random(); public static void Shuffle<T>(this IList<T> list) { int n = list.Count; while (n > 1) { n--; int k = rng.Next(n + 1); T value = list[k]; list[k] = list[n]; list[n] = value; } } } public class Program { public static void Main() { //create array int[] a = new int[5]; for (int i = 0; i < a.Length; ++i) a[i] = i; } Shuffler.Shuffle(a) for (int i = 0; i < a.Length; ++i) { Console.Write("{0}\t", a); Console.WriteLine(); } } }
1 Like