在c#中使用group by

本文关键字:group by | 更新日期: 2023-09-27 18:07:38

谁能解释一下这段代码是做什么的?我不太明白单词串是如何被分组的。是把每个单词的第一个字母分组吗?

// 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() };

在c#中使用group by

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

LINQ文档和示例应该让你开始阅读和编写这样的代码。

// 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