In object -oriented programming, the situation of multiple objects sharing specific attributes is common. For example, the "PERSON" class contains "ID" and the car list. In order to clearly and efficiently aggregate a car associated with each unique ID, we can use Linq's "Groupby" operator.
GroupBy operator divides the object sequence into a smaller group according to the value of the specified key. In our "Person" category, we can use the "Personid" property as a key to group objects. This will effectively create a structure similar to a dictionary, where the key is the only "Personid" value, and the value is a list of "car" values associated with each "Personid".
code example
In order to group the "Person" object and retrieve the corresponding car list according to "Personid", we can use the following Linq query expression:
or, we can use non -query expressions to achieve the same results:
var results = from p in persons group p.car by p.PersonId into g select new { PersonId = g.Key, Cars = g.ToList() };
var results = persons.GroupBy( p => p.PersonId, p => p.car, (key, g) => new { PersonId = key, Cars = g.ToList() });
"Personid": The only ID of a person
"Cars": The list of all the car owned by the person
In order to be consistent with the naming agreement. It is recommended to use "Personid" instead of "Personid" when using the attribute name.
The above is the detailed content of How Can LINQ's GroupBy Operator Efficiently Aggregate Objects Based on Shared Property Values?. For more information, please follow other related articles on the PHP Chinese website!