无法获得Linq外部组的关键

时间:2014-02-06 11:27:51

标签: c# linq linq-to-objects

我通过Linq建立了一个嵌套组。我根据学生姓名的第0个元素创建了第一组。第二组是基于学生的名字。我无法获得外部组的关键,即'h'或'a'。请帮助。

代码:

List<student> li = new List<practice.student>()
{
    new student(){name="harry",marks=50},
    new student(){name="harry",marks=60},
    new student(){name="hermione",marks=50},
    new student(){name="hermione",marks=60},
    new student(){name="ajax",marks=60},
    new student(){name="ajax",marks=70},
    new student(){name="abby",marks=60},
    new student(){name="abby",marks=70}
};

var query1 = li.GroupBy(t => t.name[0]).Select(t => t.GroupBy(s => s.name));

foreach (var item in query1) 
{
    Console.WriteLine(item.Select(t=>t.Key));

    foreach (var item1 in item) 
    {
        Console.WriteLine("Key:"+item1.Key);

        foreach (var item2 in item1) 
        {
            Console.WriteLine(item2.name+","+item2.marks);
        }
        Console.WriteLine();
    }
    Console.WriteLine();
}

输出:

System.Linq.Enumerable+WhereSelectEnumerableIterator`2[System.Linq.IGrouping`2[S
ystem.String,practice.student],System.String]
Key:harry
harry,50
harry,60

Key:hermione
hermione,50
hermione,60


System.Linq.Enumerable+WhereSelectEnumerableIterator`2[System.Linq.IGrouping`2[S
ystem.String,practice.student],System.String]
Key:ajax
ajax,60
ajax,70

Key:abby
abby,60
abby,70

1 个答案:

答案 0 :(得分:2)

您可以使用匿名类型,例如:

var query1 = li.GroupBy(t => t.name[0]).Select(t => new {Letter=t.Key, Students=t.GroupBy(s => s.name)});

foreach (var item in query1) 
{
    Console.WriteLine(item.Letter);
    foreach (var item1 in item.Students) 
    {
        Console.WriteLine("Key:" + item1.Key);
        foreach (var item2 in item1) 
        {
            Console.WriteLine(item2.name+","+item2.marks);
        }
        Console.WriteLine();
    }
    Console.WriteLine();

}

或者,为了缩短您的代码,只需在GroupBy循环中使用foreach

foreach(var letter in li.GroupBy(l => l.name[0]).OrderBy(l => l.Key))
{
    Console.WriteLine("Letter:" + letter.Key);
    foreach (var student in letter.GroupBy(l => l.name).OrderBy(l => l.Key)) 
    {
        Console.WriteLine(String.Format("\n\tKey: {0}", student.Key));
        foreach (var mark in student.OrderBy(s => s.marks)) 
            Console.WriteLine(String.Format("\t\t{0}, {1}", mark.name, mark.marks));
    }
    Console.WriteLine();
}

输出:

Letter:a

  Key: abby
    abby, 60
    abby, 70

  Key: ajax
    ajax, 60
    ajax, 70

Letter:h

  Key: harry
    harry, 50
    harry, 60

  Key: hermione
    hermione, 50
    hermione, 60