Home > Backend Development > C#.Net Tutorial > .NET Framework - Detailed explanation of 'grouping' technical code in collections and LINQ

.NET Framework - Detailed explanation of 'grouping' technical code in collections and LINQ

黄舟
Release: 2017-03-18 13:13:28
Original
1598 people have browsed it

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>
Copy after login

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")
            };
Copy after login

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);
Copy after login

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>
Copy after login

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());
Copy after login

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}));}
Copy after login

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, ...}
Copy after login

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());
        }
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template