We often group based on one or some attributes in a memory collection, such as List, and display statistics. The easiest way to think of is to traverse the List instance based on a certain key attribute and convert it into the following dictionary type
Dictionary<string, List<MyObject>
For example, given cars,
List<Car> cars = new List<Car>(){ new Car(1,"audiA6","private"), new Car(2,"futon","merchant"), new Car(3,"feiren","bike"), new Car(4,"bukon","private"), new Car(5,"baoma","private"), new Car(6,"dayun","merchant") };
wants to use id as the key, The value of Car is converted into a dictionary idCarDict. In addition to traversing this method, which has the most complicated logic and requires the most code, we can also directly use the ToDictionary method,
ar idCarDict = cars.ToDictionary(car=>car.id);
However, this method has limitations, and the key code corresponds There can only be one instance of the object, that is, the returned type is,
Dictionary<string,Object>
This is bad, because one key code may correspond to multiple instances, so you have to use GroupBy. First group by key code, and then convert into a dictionary.
For example, we want to use type as the key to get multiple cars under this model.
Dictionary<string, List<Car>> typeCarDict = cars.GroupBy(car => car.type). ToDictionary(g => g.Key, g => g.ToList());
This conversion code is simple and much better than the following traversal logic!
var dict = new Dictionary<string,List<Car>>();foreach(var car in cars) { if(dict.Contains(car.type)) dict[car.type].Add(car); else dict.Add(car.type,new List<Car>(){car}));}
This solves the problem of one key code corresponding to multiple instances. Then the problem of multiple key codes corresponding to multiple instances can be achieved with the help of GroupBy on the List? Can't be achieved.
At this time, you need to write a Linq statement to combine multiple key codes into a new object.
new {key1, key2, ...}
As an example, we have such a collection, and the elements in the collection are ValPair objects. , this object contains two integer elements, Val1 is the smaller one, and Val2 is relatively larger. How to group according to the combination of Val1 and Val2?
Please see the following logic:
static void printfDuplicateCompare(List<ValPair> compares) { //按组合键分组后,每组元素个数大于2的分组,按降序排序 var rtnByVal1 = from item in compares group item by new { item.Val1, item.Val2 } into g where g.Count()>1 orderby g.Count() descending select g; //按Val1和Val2组合为字典键,元素个数为值 var dict = rtnByVal1.ToDictionary(g => g.Key,g=>g.Count()); }
Summary
List's GroupBy can only be grouped based on one key. If you need to group based on multiple key combinations, you must write a Linq statement combination.
The above is the detailed content of .NET Framework - Detailed explanation of 'grouping' technical code in collections and LINQ. For more information, please follow other related articles on the PHP Chinese website!