【问题标题】:Adding Random Element to GenericList in C#在 C# 中将随机元素添加到通用列表
【发布时间】:2021-12-29 18:30:49
【问题描述】:

我正在尝试使用数据结构制作一个简单的送餐系统。我在 ArrayList 中保存了 Neighborhood 名称,并在 GenericList 中保存了 Delivery Count、Food Name 和它的计数。我画了原理图并附上了照片。

我编写了打印“Hood Name and it's delivery count”的程序,我的代码和输出在这里:

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);
            }

我的输出是:

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

我怎样才能得到这样的输出:

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 |.....................

我猜我必须像这样制作食物清单和计数清单:

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

我需要创建配送类(包含膳食名称、数量字段)。然后我必须用相关邻域中的 Delivery 对象的数量填充 ArrayList 中的每个通用列表。我可以创建一个食物列表并从中随机选择食物信息。对于这个项目,我们可以假设每次交付只能包含一种餐食(包括多少)。

我是 C# 和数据结构的新手,非常感谢您的帮助。

【问题讨论】:

    标签: c# for-loop arraylist data-structures generic-list


    【解决方案1】:

    我会使用Lists 的对象来定义您的数据结构。然后用LINQ进行查询、操作等。我认为它会更灵活,让你更接近你想要的。像这样的:

    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 = 2,
                    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>();
        }
    }
    

    见:https://dotnetfiddle.net/kN103N

    输出:

    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)
    

    【讨论】:

    • 我必须有 string[] HoodName = { "Cherryhood", "NewCastle", "Greenlight", "Summerlin", "Westcity", "Paradise", "Legions", "Flamingos" } ; int[] TeslimatSayisi = { 4, 2, 7, 2, 7, 3, 0, 1 };
    • TeslimatSayisi 表示每个社区的交付计数。
    • 我认为您不应该将交付计数存储在这样的数组中。我假设您希望能够添加和删除交付。如果将计数存储在数组中,则始终必须返回并更新数组。像我上面那样构建数据会更有意义,这样您就可以随时查询计数并获取当前数字。
    • 至于'我必须有string[]':如果你真的需要,你仍然可以做到。我只是提供了一些示例代码来构建虚拟数据。更仔细地查看我提供的类,以及我为元素提取 Count 的 LINQ 查询/方式
    【解决方案2】:

    我注意到的第一件事是引擎盖类没有交货清单,所以我添加了一个。其次,我从主要方法中提取了方法,它们负责。结果就是这样:

        public static void Main()
        {
            initDictionary();
            printOutDeliveries();
        }
    
         static void printOutDeliveries()
        {
            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;
    }
    

    【讨论】:

    • 哟兄弟感谢您的帮助。我尝试在我的编译器上运行代码,但出现了很多错误。我按照编译器的建议修复了错误,但是当我运行代码时,我没有得到任何输出。
    【解决方案3】:

    我对我的代码进行了一些更改,并部分解决了它。这是我的代码:

    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);
                }
            }
        }
    }
    

    输出:

    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,
    

    【讨论】:

      猜你喜欢
      • 2021-09-21
      • 1970-01-01
      • 1970-01-01
      • 2016-02-17
      • 1970-01-01
      • 1970-01-01
      • 2013-01-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多