2017-07-04 97 views
0

我遇到了一些麻煩。我應該實施GroupBy的定義。 我不確定如何將值分組,可以有人幫助我嗎?不能使用LINQIGrouping,IEnumerable和Pairs

對的定義:

class Pair<K, V> { 
    public Pair(K key, V value) { 
     Key = key; 
     Value = value; 
    } 
    public K Key { get; set; } 
    public V Value { get; set; } 
} 

主:

string[] src = { "ola", "super", "isel", "ole", "mane", "xpto", "aliba" }; 
foreach (Pair<int, IEnumerable<string>> pair in src.GroupBy(s => s.Length)) 
{ 
    Console.WriteLine("{0}: {1}", pair.Key, string.Join(", ", pair.Value)); 
} 

輸出

/** 
* Output: 
* 3: ola, ole 
* 5: super, aliba 
* 4: isel, mane, xpto 
*/ 
+0

'GroupBy'不會返回'Pair '。它的類型是'System.Linq.GroupedEnumerable '。 –

回答

2

要從IEnumerable<IGrouping<TKey, TSource>> you'll做出Pair<int, IEnumerable<string>>需要這樣:

foreach (Pair<int, IEnumerable<string>> pair in src.GroupBy(s => s.Length) 
    .Select(x => new Pair<int, IEnumerable<string>>(x.Key, x.ToList())) 
) 

但我不確定爲什麼有人應該使用它。

很容易使用僅僅是這樣的:

foreach (var pair in src.GroupBy(s => s.Length)) 
{ 
    Console.WriteLine("{0}: {1}", pair.Key, string.Join(", ", pair.ToList())); 
} 

這樣,你甚至dn't需要你Pair -class。

+0

不確定使用「字典」有什麼問題? – Rahul

+0

@Rahul它會將整個集合放入內存中,例如當集合很大時這是一個壞主意。其次爲什麼你應該寫一本字典呢?它沒有增加任何價值來自己迭代每個組。 – HimBromBeere

+0

你的解釋是錯誤的......評論意思是OP,而不是你兄弟。我的意思是用字典來代替'Pair >' – Rahul

0

GroupBy(即Select)之後的代碼會將數據投影到您嘗試使用的Pair類中。

using System; 
using System.Collections.Generic; 
using System.Linq; 

namespace Test 
{ 
    public class Program 
    { 
     class Pair<K, V> 
     { 
      public Pair(K key, V value) 
      { 
       Key = key; 
       Value = value; 
      } 
      public K Key { get; set; } 
      public V Value { get; set; } 
     } 

     static void Main(string[] args) 
     { 
      string[] src = { "ola", "super", "isel", "ole", "mane", "xpto", "aliba" }; 
      var pairs = src.GroupBy(s => s.Length) 
       .Select(@group => new Pair<int, IEnumerable<string>>(@group.Key, @group)); 

      foreach (var pair in pairs) 
      { 
       Console.WriteLine("{0}: {1}", pair.Key, string.Join(", ", pair.Value)); 
      } 

      Console.ReadLine(); 
     } 
    } 
}