Initializing Lookup

前端 未结 6 1630
轮回少年
轮回少年 2021-01-07 17:47

How do i declare a new lookup class for a property in the object initializer routine in c#?

E.g.

new Component() { ID = 1, Name = \"MOBO\", Category          


        
6条回答
  •  醉酒成梦
    2021-01-07 18:12

    Lookups work with the same concept as Dictionaries, the difference is that Dictionaries map a key to a single value, whereas a Lookup map a key to many values.

    This also means that:

    ILookup
    

    could be seen as:

    IDictionary>
    

    You basically would want to use ILookup when you want to map many objects/values to a same key. You can build an ILookup from any list of objects, where you want to group these objects by some property. See:

    public class Product
    {
        public string Name { get; set; }
        public string Category { get; set; }
        public decimal Price { get; set; }
    }
    
    var products = new List();
    products.Add(new Product { Name = "TV", Price = 400, Category = "Electronics" });
    products.Add(new Product { Name = "Computer", Price = 900, Category = "Electronics" });
    products.Add(new Product { Name = "Keyboard", Price = 50, Category = "Electronics" });
    products.Add(new Product { Name = "Orange", Price = 2, Category = "Fruits" });
    products.Add(new Product { Name = "Grape", Price = 3, Category = "Fruits" });
    
    // group by category
    ILookup lookup = products.ToLookup(prod => prod.Category);
    
    foreach (var item in lookup)
    {
        // this first loop would run two times
        // because there are two categories: Electronics and Fruits
        string category = item.Key;
        decimal totalPriceForCategory = item.Sum(i => i.Price);
    
        foreach (var product in item)
        {
            // for the electronics, this would loop three times
            // for the fruits, this would loop two times
            string name = product.Name;
            decimal price = product.Price;
        }
    }
    

    You could also get all the products for a category like this:

    IEnumerable eletronics = lookup["Electronics"];
    IEnumerable fruits = lookup["Fruits"];
    

提交回复
热议问题