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

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

问题描述

如何使用 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 };
    } 
}

我有两个人名单:

list1:
1, A
2, B

list2: 
2, C
3, D

我想要如下结果

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

任何帮助!

推荐答案

我强烈建议不要使用字符串连接来表示此信息;如果您想稍后从合并列表中取回原始数据,您将需要执行不必要的字符串操作.此外,如果您决定向类添加其他属性,合并版本(就其现状而言)将变得有损.

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.

最好摆脱 Merge 方法并使用适当的数据结构,例如多映射,每个映射都可以将一组键映射到一个或多个值.Lookup 类可以用于此目的:

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 对人员进行分组,然后将每个组聚合为一个 单个 人员提供了 Merge 方法:


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 合并两个列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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