如何从两个列表中进行分组? [英] How do I GroupBy from two Lists?

查看:87
本文介绍了如何从两个列表中进行分组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个IEnumerable,一个具有必备"键基,另一个具有许多具有各种拼写方式的键(相同的值,但包含转义序列,大写字母等).我想在第一个列表的每个键到与第二个列表中的字符串对应的所有键之间建立一个映射(谓词为bool IsPossibleMatch(string a, string b))

I have two IEnumerable, one with a "Must-have" base of keys, the other with a lot of keys with all kinds of spellings (the same values but containing escape-sequences, different capitalization, etc). I want to create a mapping between every key of the first List to all the ones that correspond with the strings in the second List (Predicate is bool IsPossibleMatch(string a, string b))

所以基本上我想要一个IGrouping<string, IEnumerable<string>>,因为那正是我要寻找的东西的结构.

So basically I want an IGrouping<string, IEnumerable<string>> because that's exactly the structure of thing I'm looking for.

我尝试了keys.GroupBy((x,y) => IsPossibleMatch(x, y))的各种版本,但其中的任何一个都无法正常工作.

I tried various versions of keys.GroupBy((x,y) => IsPossibleMatch(x, y)) but couldn't get any of them to work.

现在我想知道:分组依据是否有可能?还是我需要以其他某种方式手动执行此操作?

Now I'm wondering : Is this even possible with group by? Or do I need to manually do this in some other kind of way?

推荐答案

以下是示例代码:

var left = new string[] {
    "key1",
    "key2",
    "key3",
    "key4",
    "key5"
};
var right = new string[]
{
    "key1",
    "Key1",
    "KEy1",
    "KEY1",
    "KeY1",
    "kEY1",
    "kEy1",
    "key2",
    "Key2",
    "KEy2",
    "KEY2",
    "KeY2",
    "kEY2",
    "kEy2"
};
var output = left.GroupJoin(
    right,
    leftStr => leftStr.ToLower(),
    rightStr => rightStr.ToLower(),
    (x,y)=>(x,y)
);
foreach (var leftKey in output)
    Console.WriteLine(leftKey.x + "->" + string.Join(",", leftKey.y));

产生以下输出:

key1->key1,Key1,KEy1,KEY1,KeY1,kEY1,kEy1
key2->key2,Key2,KEy2,KEY2,KeY2,kEY2,kEy2
key3->
key4->
key5->

这篇关于如何从两个列表中进行分组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆