如何使用LINQ to合并两个列表? [英] How to merge two lists using LINQ?

查看:471
本文介绍了如何使用LINQ to合并两个列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何合并使用LINQ两个列表如下所示:

How to merge two lists using LINQ like the following:

class Person
{
    public int ID { get; set;}
    public string Name { get; set;}
    public Person Merge( Person p)
    {
         return new Person { ID = this.ID, Name = this.Name + " " + p.Name };
    } 
}

我的人,两个List

I have two List of person:

list1:
1, A
2, B

list2: 
2, C
3, D

我想要的结果类似下面的

I want the result like the following

result: 
1, A
2, B C
3, D

任何帮助!

推荐答案

我会强烈建议不要使用字符串连接来重新present这一信息;您将需要执行不必要的字符串操作,如果你想从合并列表中获取原始数据回来。此外,合并后的版本(因为它代表)将成为有损的,如果你决定附加属性添加到类。

I would strongly recommend against using string-concatenation to represent this information; you will need to perform unnecessary string-manipulation if you want to get the original data back later from the merged list. Additionally, the merged version (as it stands) will become lossy if you ever decide to add additional properties to the class.

preferably,摆脱了合并方法,并使用合适的数据结构,如多重映射,可以每个地图键集合到一个或多个值。该 查找< TKEY的,TElement> 类可以达到这个目的:

Preferably, get rid of the Merge method and use an appropriate data-structure such as a multimap that can each map a collection of keys to one or more values. The Lookup<TKey, TElement> class can serve this purpose:

var personsById = list1.Concat(list2)
                       .ToLookup(person => person.ID);


总之,要回答这个问题的询问,您可以连接两个序列,然后按自己的 ID的人,然后汇总各组成的的人与所提供的合并方法:


Anyway, to answer the question as asked, you can concatenate the two sequences, then group persons by their ID and then aggregate each group into a single person with the provided Merge method:

var mergedList = list1.Concat(list2)
                      .GroupBy(person => person.ID)
                      .Select(group => group.Aggregate(
                                         (merged, next) => merged.Merge(next)))
                      .ToList();

修改:在重新阅读,只是意识到,因为有串联需要的两个的名单

EDIT: Upon re-reading, just realized that a concatenation is required since there are two lists.

这篇关于如何使用LINQ to合并两个列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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