IGrouping,IEnumerable和Pairs

时间:2017-07-04 12:19:41

标签: c# ienumerable

我遇到了一些麻烦。我应该实现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
*/

2 个答案:

答案 0 :(得分:2)

要从 <IfModule mod_rewrite.c> RewriteEngine On RewriteRule ^Product/Category/([^/]*)$ /Product/index.php?category=$1 [L] RewriteRule ^Pages/([^/]*)$ /Allpages/?Pages=$1 [L] RewriteRule ^Products/([^/]*)$ /Product/ProductPage.php?product=$1 [L] RewriteCond %{HTTP:X-Forwarded-Proto} !https RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} </IfModule> 制作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())); } - 类。

答案 1 :(得分: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();
        }
    }
}