开发者

Splitting a collection with LINQ

开发者 https://www.devze.com 2023-02-10 21:35 出处:网络
I\'m sure there\'s an easy way to do this but I can\'t come up with it... I have a collection with a Group string field. What I\'d like to do is split that collection into (n) number of collections f

I'm sure there's an easy way to do this but I can't come up with it...

I have a collection with a Group string field. What I'd like to do is split that collection into (n) number of collections for each Group. I'll end up with a loop 开发者_JAVA百科similar to this:

foreach (var group in groups)
{
   foreach (var item in group)
   {
      //process item.
   }
}

Any guidance out there??? Thanks!

Edit for example:

Given this:

var people = new List();
people.Add(new Person { FirstName = "John", LastName = "Doe" });
people.Add(new Person { FirstName = "Jane", LastName = "Doe" });
people.Add(new Person { FirstName = "Bob", LastName = "Barker" });
people.Add(new Person { FirstName = "Billy", LastName = "Barker" });
people.Add(new Person { FirstName = "Billy", LastName = "Bob" });

I'd like to get a collection with 3 elements. Element 1 will be a collection of people (the Does), Element 2 will be a collection of people (The Barkers), Element 3 will be a collection with Billy Bob.


Maybe, GroupBy will help?

var grouped = groups.GroupBy(g => g.Group);


EDIT: made it fit the example. We group people by their last name, iterate over the groups, then iterate over each person inside each group

var groupedCollection = from person in people
                        group person by person.LastName; // or use .GroupBy()
foreach (var group in groupedCollection)
{
    var lastName = group.Key;
    foreach (var person in group)
    {
        // do stuff with person
    }
}

Read up on more grouping samples here

0

精彩评论

暂无评论...
验证码 换一张
取 消