[英]IGrouping, IEnumerable and Pairs
我遇到了麻烦。 我应该实现GroupBy
的定义。 我不确定如何将值成对分组,有人可以帮我吗? 不能使用LINQ
对的定义:
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
*/
要从IEnumerable<IGrouping<TKey, TSource>>
创建Pair<int, IEnumerable<string>>
IEnumerable<IGrouping<TKey, TSource>>
您将需要以下内容:
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()));
}
这样,您甚至都不需要Pair
类。
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();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.