在C#中使用group by

时间:2013-04-06 12:50:14

标签: c# linq

有人能解释一下这个代码示例是做什么的吗?我无法完全理解字符串是如何分组的。它是采用每个单词的第一个字母并以某种方式对它们进行分组吗?

// Create a data source. 
        string[] words = { "apples", "blueberries", "oranges", "bananas", "apricots" };

        // Create the query. 
        var wordGroups1 =
            from w in words
            group w by w[0] into fruitGroup
            where fruitGroup.Count() >= 2
            select new { FirstLetter = fruitGroup.Key, Words = fruitGroup.Count() };

2 个答案:

答案 0 :(得分:3)

LINQ查询按照第一个字符对所有单词进行分组。然后删除所有只包含一个元素的组(=保留所有具有两个或更多元素的组)。最后,这些组被填充到新的匿名对象中,其中包含从该字母开头找到的第一个字母和单词数。

LINQ Documentationsamples应该让您开始阅读和编写类似的代码。

答案 1 :(得分:0)

// Create a data source. 
string[] words = { "apples", "blueberries", "oranges", "bananas", "apricots" };

// Create the query. 
var wordGroups1 =
    from w in words                  //w is every single string in words
    group w by w[0] into fruitGroup  //group based on first character of w
    where fruitGroup.Count() >= 2    //select those groups which have 2 or more members
                                     //having the result so far, it makes what is needed with select
    select new { FirstLetter = fruitGroup.Key, Words = fruitGroup.Count() };

另一个例子。在数组中显示字符串长度的频率:

var wordGroups1 =
    from w in words                  
    group w by w.Length into myGroup  
    select new { StringLength = myGroup.Key, Freq = myGroup.Count() };

//result: 1 6-length string
//        1 11-length string
//        2 7-length string
//        1 8-length string