使用LINQ拆分集合

时间:2011-02-17 14:43:59

标签: c# linq

我确信有一种简单的方法可以做到这一点,但我无法想出来......

我有一个带有组字符串字段的集合。我想做的是将该集合分成(n)每个集合的集合数量。我最终会得到一个类似于此的循环:

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

有任何指导吗?谢谢!

编辑例如:

鉴于此:

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

我想要一个包含3个元素的集合。元素1将是人物的集合(The Does),元素2将是人物的集合(The Barkers),元素3将是与Billy Bob的集合。

2 个答案:

答案 0 :(得分:5)

也许,GroupBy会有所帮助吗?

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

答案 1 :(得分:2)

编辑:使它适合这个例子。我们按照他们的姓氏对人进行分组,迭代这些组,然后迭代每个组内的每个人

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
    }
}

阅读更多分组样本here