简体   繁体   中英

Adding Random Element to GenericList in C#

I am trying to make a simple food delivery system by using data structures. I hold the Neighborhood names in an ArrayList and I hold the Delivery Count, Food Name and it's count in GenericList. I drew the schematic and attached the photo.

原理图(复合数据结构)

I coded the program which prints the "Hood Name and it's delivery count" my code and my outputs are here:

using System;
using System.Collections;
using System.Collections.Generic;

namespace temp

{
    
    internal class delivery
    {
        public string food;
        public int count;

    }
    internal class Hood
    {
        public string Name;
        public int Number;
    }
    class programm
    {
        static void Main(string[] args)
        
        {

            string[] HoodName = { "Cherryhood", "NewCastle", "Greenlight", "Summerlin", "Westcity", "Paradise", "Legions", "Flamingos" };
            int[] TeslimatSayisi = { 4, 2, 7, 2, 7, 3, 0, 1 };
            ArrayList arrayList = new ArrayList();
            int counter = 0;
            List<Hood> genericList;
            Hood ClassExample;

            for (int i = 0; i < HoodName.Length;)
            {
                genericList = new List<Hood>();
                int elementCount = (int)Math.Pow(2, counter);
                for (int j = 0; j < elementCount; j++)
                {
                    ClassExample = new Hood();
                    ClassExample.Name = HoodName[i];
                    ClassExample.Number = TeslimatSayisi[i];
                    genericList.Add(ClassExample);
                    i++;
                    if (i == HoodName.Length) break;
                }
                arrayList.Add(genericList);
                counter++;
            }
            int counter2 = 0;
            foreach (List<Hood> temp in arrayList)
            {
                foreach (Hood temp2 in temp)
                    Console.WriteLine("Hood: " + temp2.Name +" | "+" Delivery Count: " + temp2.Number);
            }

My outputs are:

Hood: Cherryhood |  Delivery Count: 4
Hood: NewCastle |  Delivery Count: 2
Hood: Greenlight |  Delivery Count: 7
Hood: Summerlin |  Delivery Count: 2
Hood: Westcity |  Delivery Count: 7
Hood: Paradise |  Delivery Count: 3
Hood: Legions |  Delivery Count: 0
Hood: Flamingos |  Delivery Count: 1

How can I get an output like this:

Hood: Cherryhood |  Delivery Count: 4 | Food's, count: Salat:2, Taco:5, Pizza:1, Burger:2
Hood: NewCastle |  Delivery Count: 2 | Food's, count: Pasta:15, Cake,7 
Hood: Greenlight |  Delivery Count: 7 | Food's, count: ................
Hood: Summerlin |  Delivery Count: 2 | ..........
Hood: Westcity |  Delivery Count: 7 |...........
Hood: Paradise |  Delivery Count: 3 |.................
Hood: Legions |  Delivery Count: 0 |...........
Hood: Flamingos |  Delivery Count: 1 |.....................

I can guess I have to make a food list and count list like this:

foods = {pizza, taco, burger, salad, pasta, cake..........}
count = {1, 5, 2, 2, 15 ,7...........}

I need to create the delivery class (containing the Meal Name, Quantity fields). Then I have to fill each of the Generic Lists in the ArrayList with the number of Delivery objects in the relevant neighborhood. I can create a food list and randomly select food information from there. For this project, We can assume that each delivery can consist of only one type of meal (including how many).

I am pretty new on C# and Data Structures thanks a lot for the help.

I would use List s of objects to define your data structure. And then LINQ to query, manipulate, etc. I think it will be more flexible and give you closer to what you want. Something like this:

using System;
using System.Collections.Generic;
using System.Linq;
                    
public class Program
{
    public static void Main()
    {
        var status = new List<Neighbourhood>{
            new Neighbourhood{
                Name = "Cherryhood",
                Id = 1,
                Orders = new List<Order>{
                    new Order{
                        Id = 300,
                        OrderItems = new List<string>{
                            "Salad",
                            "Taco",
                            "Pizza"
                        }
                    },
                    new Order{
                        Id = 301,
                        OrderItems = new List<string>{
                            "Cake",
                            "Taco",
                            "Pasta",
                            "Burger"
                        }
                    },
                    new Order{
                        Id = 302,
                        OrderItems = new List<string>{
                            "Salad",
                            "Pasta"
                        }
                    }
                }
            },
            new Neighbourhood{
                Name = "Newcastle",
                Id = 1,
                Orders = new List<Order>{
                    new Order{
                        Id = 400,
                        OrderItems = new List<string>{
                            "Salad",
                            "Taco",
                            "Pizza"
                        }
                    },
                    new Order{
                        Id = 401,
                        OrderItems = new List<string>{
                            "Cake",
                            "Taco",
                            "Pasta"
                        }
                    },
                    new Order{
                        Id = 402,
                        OrderItems = new List<string>{
                            "Salad",
                            "Pasta"
                        }
                    }
                }
            }
        };
        Console.WriteLine($"Neighbourhoods: {status.Count}");
        foreach(var neighbourhood in status){
            Console.WriteLine($"Neighbourhood: {neighbourhood.Name}");
            Console.WriteLine($"Total Orders: {neighbourhood.Orders.Count}");

            var allOrderItems = neighbourhood.Orders.SelectMany(i => i.OrderItems).ToList();
            Console.WriteLine($"Total Ordered Items: {allOrderItems.Count}");
            
            var groupedOrderItems = allOrderItems
                .GroupBy(i=>i)
                .Select(i => new {
                        Name = i.Key,
                        Total = i.Count()
                    })
                .OrderBy(i => i.Name)
                .ToList();
            
            foreach(var groupedOrderItem in groupedOrderItems){
                Console.WriteLine($"Order Item: {groupedOrderItem.Name} ({groupedOrderItem.Total})");
            }
        }
    }
}

public class Neighbourhood{
        public string Name {get;set;}
        public int Id {get;set;}
        public List<Order> Orders;

        public Neighbourhood(){
            Orders = new List<Order>();
        }
    }

public class Order{
    public int Id {get;set;}
    public List<string> OrderItems {get;set;}
    
    public Order(){
        OrderItems = new List<string>();
    }
}

See: https://dotnetfiddle.net/kN103N

Output:

Neighbourhoods: 2
Neighbourhood: Cherryhood
Total Orders: 3
Total Ordered Items: 9
Order Item: Burger (1)
Order Item: Cake (1)
Order Item: Pasta (2)
Order Item: Pizza (1)
Order Item: Salad (2)
Order Item: Taco (2)
Neighbourhood: Newcastle
Total Orders: 3
Total Ordered Items: 8
Order Item: Cake (1)
Order Item: Pasta (2)
Order Item: Pizza (1)
Order Item: Salad (2)
Order Item: Taco (2)

The first thing I noticed was that the hood class had not a list of deliveries so I added one. Secondly I extracted the methods from the main method with their responsibility. And that was the result:

    public static void Main()
    {
        initDictionary();
        printOutDelveries();
    }

     static void printOutDelveries()
    {
        foreach (var hood in hoods)
        {
            string foodNumbers="";
            foreach (var del in hood.Value.Deliveries)
            {
               foodNumbers += del.food + ": " + del.count + ", ";
            }
            Console.WriteLine("Hood: " + hood.Key + " | Deliver Count: " + hood.Value.Number + " Foods count: "+foodNumbers);

        }
    }

     static Dictionary<string, Hood> hoods = new Dictionary<string, Hood>();

     static void initDictionary()
    {
        string[] HoodName = { "Cherryhood", "NewCastle", "Greenlight", "Summerlin", "Westcity", "Paradise", "Legions", "Flamingos" };
        int[] TeslimatSayisi = { 4, 2, 7, 2, 7, 3, 0, 1 };
        int i = 0;
        foreach (var name in HoodName)
        {
            hoods.Add(name, new Hood()
            {
                Name = name,
                Number = TeslimatSayisi[i++],
                Deliveries = GetRandomDeliveries()
            });
        }
    }

    static List<delivery> GetRandomDeliveries()
    {
        List<string> foods = new List<string> { "Salat", "Taco", "Pizza", "Burger", "Pasta", "Cake" };
        List<delivery> deliveries = new List<delivery>();
        var randMaxVal = foods.Count - 1;
        var random = new Random();
        var forlooplength = random.Next(randMaxVal);
        for (int i = 0; i < forlooplength; i++)
        {
            var rand = random.Next(randMaxVal);
            deliveries.Add(new delivery()
            {
                food = foods[rand]
            });
            foods.RemoveAt(rand);
        }
        return deliveries;
    }
}
internal class delivery
{
    public string food;
    public int count => new Random().Next(10);
}
internal class Hood
{
    public string Name;
    public int Number;
    public List<delivery> Deliveries;
}

I made some changes on my code and I partly solved it. Here is my code:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace temp

{

    internal class delivery
    {
        public string food;
        public int count;

    }
    internal class Hood
    {
        public List<delivery> deliveryList;
        public string Name;
        public int Number;
    }
    class program
    {
        static void Main(string[] args)

        {
            List<string> food_names = new List<string> { "Burger", "Pizza", "Toast", "Chicken", "Taco", "Ice Cream", "Tomato", "Potato", "Salad" };
            List<int> max_food = new List<int> { 4, 5, 10, 7, 2, 6, 3, 7, 9 };
            ArrayList HoodName = new ArrayList(){
                    "Cherryhood", "NewCastle", "Greenlight", "Summerlin", "Westcity", "Paradise", "Legions", "Flamingos"
                };
            ArrayList TeslimatSayisi = new ArrayList() { 4, 2, 7, 2, 7, 3, 0, 1 };
            List<Hood> genericList = new List<Hood>();
            Hood ClassExample;

            for (int i = 0; i < HoodName.Count; i++)
            {
                ClassExample = new Hood();
                ClassExample.deliveryList = new List<delivery>();
                ClassExample.Name = (string)HoodName[i];
                ClassExample.Number = (int)TeslimatSayisi[i];
                genericList.Add(ClassExample);
            }

            foreach (Hood element in genericList)
            {
                delivery delivery_example;
                for (int i = 0; i < element.Number; i++)
                {
                    delivery_example = new delivery();
                    delivery_example.food = "Burger";
                    delivery_example.count = 5;
                    element.deliveryList.Add(delivery_example);
                }
            }

            foreach (Hood temp in genericList)
            {
                List<string> copy1 = food_names.ToList();
                List<int> copy2 = max_food.ToList();
                string temp1 = "Foods, count: ";
                Random rnd = new Random();
                foreach (delivery d in temp.deliveryList)
                {
                    if (copy1.Count != 0)
                    {
                        int r = rnd.Next(copy1.Count);
                        string food = copy1[r];
                        string num = copy2[r].ToString();
                        copy1.Remove(food);
                        copy2.Remove(int.Parse(num));
                        temp1 += food;
                        temp1 += ":";
                        temp1 += num;
                        temp1 += ", ";
                    }
                    else
                    {
                        temp1 += "Ran out of food, ";
                    }

                }
                Console.WriteLine("Hood: " + temp.Name + " | " + " Delivery Count: " + temp.Number + " | " + temp1);
            }
        }
    }
}

The outputs:

Hood: Cherryhood |  Delivery Count: 4 | Foods, count: Ice Cream:6, Potato:7, Chicken:2, Salad:9,
Hood: NewCastle |  Delivery Count: 2 | Foods, count: Ice Cream:6, Burger:4,
Hood: Greenlight |  Delivery Count: 7 | Foods, count: Burger:4, Taco:2, Salad:9, Tomato:3, Pizza:5, Chicken:7, Ice Cream:6,
Hood: Summerlin |  Delivery Count: 2 | Foods, count: Salad:9, Potato:7,
Hood: Westcity |  Delivery Count: 7 | Foods, count: Burger:4, Ice Cream:6, Taco:2, Tomato:3, Toast:10, Pizza:5, Chicken:7,
Hood: Paradise |  Delivery Count: 3 | Foods, count: Ice Cream:6, Salad:9, Toast:10,
Hood: Legions |  Delivery Count: 0 | Foods, count:
Hood: Flamingos |  Delivery Count: 1 | Foods, count: Potato:7,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM