如何以这种方式遍历列表?

时间:2012-11-15 10:29:40

标签: c# linq list foreach

我有一个对象列表,如下所示:

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"

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

我该怎么办?通过...分组?嗯...

4 个答案:

答案 0 :(得分:8)

是的,有一个小组:

foreach (var group in items.GroupBy(i => i.ID))
{
    foreach (var item in group)
    {
    } 
}

答案 1 :(得分: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)
    {
        // ...
    } 
}

答案 2 :(得分: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。我执行完全相同的功能,它只是更冗长:)

答案 3 :(得分:0)

为什么在使用sort时使用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)