In this series, I learned some very useful functions from C # together with everyone. For some people, they may be inconspicuous, so they are often ignored. They won't yell: "Use me! I will save you a lot of time and make your code more concise !" -But these words will emerge from the minds of programmers who are familiar with them.
Okay! Let's take a look at ToLookup:
Translated from:
C #/. NET Little Wonders: The ToLookup () LINQ Extension MethodBackground
Let's first create a simple class to represent the product, the product has ID, category, and price. This class has nothing special:
public sealed class Product { public int Id { get; set; } public string Category { get; set; } public double Value { get; set; } public override string ToString() { return string.Format("[{0}: {1} - {2}]", Id, Category, Value); } }
Then we add a function to get a list of products. Of course, you can also read it from the database:
public static List<Product> GetList() { var products = new List<Product> { new Product {Id = 1, Category = "Electronics", Value = 15.0}, new Product {Id = 2, Category = "Groceries", Value = 40.0}, new Product {Id = 3, 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}, }; return products; }
One task is to list an item list by category, which is very easy. You can use GroupBy:
foreach (var group in products.GroupBy(p => p.Category)) { Console.WriteLine(group.Key); foreach (var item in group) { Console.WriteLine("" + item); } }
Everything looks good, no problem.
When we useGroupBy ()Delayed execution is used for extension methods. This means that when you traverse the set, the next project that will appear may or may not be loaded. This is a huge performance improvement, but it can cause interesting side effects.
In useGroupBy (), It actually creates a group when the first item is used, insteadGroupBy ()When called for the first time.
Consider: If you load data from the database and want to combine the data and store it for quick search. See the following code: