|
|
Posted on 12/19/2023 8:30:35 PM
|
|
|
|

Requirements: Read other people's technical blogs, find that some collections call the ToLookup method, this method has not been touched, and then query the relevant materials to learn the use of this extension method. The ToLookup method returns a value of ToLookup<TSource, TKey> a one-to-many dictionary for mapping keys to a collection of values.
GroupBy vs. ToLookup
GroupBy and ToLookup are both LINQ extension methods for grouping collections, and the main difference between the two is the return type and usage.
The GroupBy method returns an IEnumerable<IGrouping<TKey, TElement>> object, where TKey is the type that represents the grouping key and TElement is the type that represents the element type. This method groups the collection according to the specified key selector and returns the grouping result as a sequence of IGrouping<TKey, TElement> objects. IGrouping<TKey, TElement> objects represent a collection of elements with the same key. You can use foreach loops or LINQ queries to iterate over grouped results. The GroupBy method is a delayed execution operation that only executes the actual grouping operation when you start iterating through its results.
The ToLookup method returns an ILookup<TKey, TElement> object, where TKey is the type that represents the grouping key and TElement is the type that represents the element type. The method groups the collection according to the specified key selector and returns the grouping result as an ILookup<TKey, TElement> object. ILookup<TKey, TElement> objects represent a collection of elements with the same key. You can use an indexer or a foreach loop to access the grouped results. Unlike GroupBy, ToLookup is an immediate action that immediately executes the grouping action and returns the result when called.
Example: A student is in a class, and a class corresponds to multiple students. The student collection contains class information, and the students of each class (or specified class) are output according to class groups.
The code is as follows:
As shown below:
Reference:The hyperlink login is visible.
|
Previous:.NET/C# Console Command Line Tools (Parameters, Options)Next:Docker base image changes for .NET 8
|