2013-04-06 52 views
1

任何人都可以解釋這個代碼示例在做什麼?我無法完全理解單詞串是如何分組的。它是採取每個單詞的第一個字母,並以某種方式將它們分組?在C#中使用羣組

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

我重複了這個來添加LINQ標記,也許您可​​以通過這種方式找到更多的幫助。 – Haedrian 2013-04-06 12:55:56

回答

3

LINQ查詢按照它們的第一個字符對所有單詞進行分組。然後它刪除所有隻包含一個元素的組(=保留所有具有兩個或更多元素的組)。最後,這些組被填充到新的匿名對象中,該對象包含以該字母開頭的第一個字母和多個單詞。

LINQ Documentationsamples應該讓你開始閱讀和編寫這樣的代碼。

+0

那麼,一旦它被分組後,字符串會是什麼樣子,對不起還在學習c# – Rifki 2013-04-06 13:00:33

+1

該組操作有一個新的結構化類型作爲其結果。它實現了[IGrouping ](http://msdn.microsoft.com/library/vstudio/bb344977.aspx),這意味着它基本上是一個鍵值對,以第一個字符作爲鍵和一個可枚舉的字符串作爲其值。 – 2013-04-06 13:08:52

+0

感謝看看現在發生了什麼 – Rifki 2013-04-06 13:12:14

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