IGrouping,IEnumerable和Pairs

问题描述 投票:0回答:2

我遇到了一些麻烦。我应该实现GroupBy的定义。我不确定如何在Pairs中对值进行分组,有人可以帮助我吗?不能使用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
*/
c# ienumerable
2个回答
2
投票

要从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级。


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();
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.