6

我有一个看起来像这样的对象列表:

ID:2000
Title:"Title 1"
Description:"My name is Marco"

ID:2000
Title:"Title 2"
Description:"My name is Luca"

ID:3000
Title:"Title 3"
Description:"My name is Paul"

ID:4000
Title:"Title 4"
Description:"My name is Anthony"

ID:4000
Title:"Title 5"
Description:"My name is Carl"

ID:4000
Title:"Title 6"
Description:"My name is Jadett"

现在,我想用 for each 浏览(遍历)它。但我想从同一个ID开始遍历它。因此,首先是单个/唯一 ID 的 foreach(2000、3000、4000,所以 3 个步骤)。然后,对于每个“ID”步骤,每个标题/描述:ID 2000 有 2 个步骤,ID 3000 有 1 个步骤,ID 4000 有 3 个步骤。列表按 ID 排序。

我该怎么做?通过...分组?嗯……

4

4 回答 4

8

是的,与一组:

foreach (var group in items.GroupBy(i => i.ID))
{
    foreach (var item in group)
    {
    } 
}
于 2012-11-15T10:33:02.207 回答
1

是的,您可以使用GroupBy.

首先是组本身:

var idGroups = items.GroupBy(i => i.ID).ToList(); // omit ToList() if scalability is more important than performance since it creates a new list but doesn't enables to enumerate the result multiple times without querying again
foreach(var idGroup in idGroups)
{
    // ...
}

然后每组的所有项目:

foreach (var idGroup in idGroups)
{
    foreach (var item in idGroup)
    {
        // ...
    } 
}
于 2012-11-15T10:40:00.677 回答
0

如果我理解正确,首先获取一个不同的 ID 列表,然后逐个遍历它们。

foreach(var id in objectList.Select(x => x.ID).Distinct())
{
    foreach(var item in objectList.Where(x => x.ID = id))
    {
        DoSomething(item);
    }
}

编辑:Amiram Korach 的答案是更好的使用GroupBy。我的执行完全相同的功能,只是更冗长:)

于 2012-11-15T10:33:58.617 回答
0

既然可以使用排序,为什么还要使用 groupby?我已经用 Tuple 做到了这一点,但用你选择的结构代替。如果您想对组进行聚合操作,Group By 很有用。你只想排序和遍历。

var list = new List<Tuple<int, string, string>>();
list.Add(Tuple.Create(4000,"Title 5", "My name is Carl"));
list.Add(Tuple.Create(2000,"Title 1", "My name is Marco"));
list.Add(Tuple.Create(4000,"Title 6", "My name is Jadett"));
list.Add(Tuple.Create(3000,"Title 3", "My name is Paul"));
list.Add(Tuple.Create(4000,"Title 4", "My name is Anthony"));
list.Add(Tuple.Create(2000,"Title 2", "My name is Luca"));

var sorted = list.OrderBy(k => k.Item1).
                  ThenBy(k => k.Item2).
                  ThenBy(k => k.Item3);

foreach (var k in sorted)
{
    Console.WriteLine(k);
}

结果是

(2000, Title 1, My name is Marco)
(2000, Title 2, My name is Luca)
(3000, Title 3, My name is Paul)
(4000, Title 4, My name is Anthony)
(4000, Title 5, My name is Carl)
(4000, Title 6, My name is Jadett)
于 2012-11-15T10:54:49.280 回答