LINQ: ToLookup() vs ToDictionary()
This is about a new feature in .net called ToLookup() a extension method on IEnumerable objects.
Most of us have used Dictionary object which will have a key value pair. But what if you want to have multiple value for a single key?
There you need this lookpu, you have use this ToLookup() extension method and make a lookup object which will have key, collection of values on it.
Lookup is a .net type which is a key value pair, where one key can point to multiple values. Dictionary is one-to-one so if you try to add the same key it will throw exception. Where as lookup is one-to-many so same key is allowed.
var products = new List
{
new Product { Id = 1, Category = "Electronics", Value = 15.0 },
new Product { Id = 1, Category = "Groceries", Value = 40.0 },
new Product { Id = 1, Category = "Garden", Value = 210.3 },
new Product { Id = 4, Category = "Pets", Value = 2.1 },
new Product { Id = 5, Category = "Electronics", Value = 19.95 },
new Product { Id = 6, Category = "Pets", Value = 21.25 },
new Product { Id = 7, Category = "Pets", Value = 5.50 },
new Product { Id = 8, Category = "Garden", Value = 13.0 },
new Product { Id = 9, Category = "Automotive", Value = 10.0 },
new Product { Id = 10, Category = "Electronics", Value = 250.0 },
};
//one to many, immutable
var lookup = products.ToLookup(p => p.Id, p => p);
var productIdsByCategory = products.ToLookup(p => p.Category, p => p.Id);
foreach(var lookupGroup in lookup[1])
{
Response.Write(lookupGroup.ToString()+"");
}
//one to one, exception will be thrown, mutable
//var dictionary = products.ToDictionary(p => p.Id, p => p);
var group = products.GroupBy(g => g.Category);
var dictionary1 = group.ToDictionary(p => p.Key, p => p.ToList());
dictionary1.Add("NewCategory", new List
{
new Product { Id = 2, Category = "NewCategory", Value = 15.0 },
new Product { Id = 2, Category = "NewCategory", Value = 40.0 },
});
While executing this I'm facing compile time errors.