如何获得以下程序的输出

时间:2011-01-17 11:50:55

标签: c# .net linq linq-to-objects

string[] groupingQuery = { "carrots", "cabbage", "broccoli", "beans", "barley" };
var queryFoodGroups = from item in groupingQuery
                      group item by item[0];

foreach (var item in queryFoodGroups)
    Console.WriteLine(item[0]);

此程序出错请建议输出

输出应该是如何根据键对结果进行分组。此查询根据单词的第一个字母返回两个组。

1 个答案:

答案 0 :(得分:1)

string[] groupingQuery = { "carrots", "cabbage", "broccoli", "beans", "barley" };

var queryFoodGroups = from item in groupingQuery 
                      group item by item[0];

foreach (IGrouping<char, string> i in queryFoodGroups)
{
    Console.WriteLine(i.Key);
    foreach (string item in i)
    {
        Console.WriteLine(item);
    }
}