2017-07-04 100 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(); 
     } 
    } 
}