Group by in LINQ with 2 attribtes

This is an already asked question, but that question is to work with 2 attributes only, I need to work with 3 attributes, So I am copy-pasting most of the text.

Let's suppose if we have a class like

class Person { 
internal int PersonID; 
internal string car  ;
internal string friend  ;
}

Now I have a list of this class: List persons;

Now this list can have instances multiple same PersonIDs, for ex.

persons[0] = new Person { PersonID = 1, car = "Ferrari" , friend = "Josh" }; 
persons[1] = new Person { PersonID = 1, car = "BMW" , friend = "Olof"     }; 
persons[2] = new Person { PersonID = 2, car = "Audi"  , friend = "Gustaf"   }; 

Is there a way I can group by personID and get the list of all the cars and friends he has? For ex. expected result would be

class Result { 
   int PersonID;
   List<string> cars; 
   List<string> friends; 
}

From what I have done so far:

IEnumerable resultsForDisplay = ResultFromSQL_Query.GroupBy(
    p => p.PersonId.ToString(),
    p => p.car,
    (key,  g) => new { PersonId = key, car = g.ToList()});

But now im stuck at getting the friend's array in resultsForDisplay


Sure, you can perform LINQ queries on the group g as well, like:

IEnumerable<Result> resultsForDisplay = from q in ResultFromSQL_Query
    group q by q.PersonID into g
    select new Result {PersonID = g.Key,cars = g.Select(x => x.car).ToList(), friends = g.Select(x => x.friend).ToList()};

Or with lambda expressions:

IEnumerable<Result> results = persons.GroupBy(x => x.PersonID)
    .Select(g => new Result { PersonID = g.Key, cars = g.Select(x => x.car).ToList(), friends = g.Select(x => x.friend).ToList()};

So you can perform any LINQ query on a group (which thus behaves as an IEnumerable<> on the elements of that grou), like a .Select(..) , but also .Sum(..) , .Average(..) and other sub queries, aggregates, etc.

链接地址: http://www.djcxy.com/p/34292.html

上一篇: 为什么WCF中的XmlRoot属性被忽略,以及如何解决这个问题

下一篇: 在LINQ中用2个属性分组