1

谁能解释这个代码示例在做什么?我不太明白字符串是如何分组的。它是否以每个单词的第一个字母并以某种方式对它们进行分组?

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

2 回答 2

2

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

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

于 2013-04-06T12:53:01.657 回答
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
于 2013-04-06T13:01:22.670 回答