c# - C#合并两个List,将id相同的对象合并为一个列表项

标签 c# .net linq list

我已经考虑过如何通过推出我自己的解决方案来解决这个问题,但我想知道 .NET 是否已经具备我想要实现的功能 - 如果是这样,我宁愿使用一些东西内置。

假设我有一个 Widget 对象的两个实例,我们称它们为 PartAPartB。每个人的信息都是从两个不同的网络服务中获取的,但两者都有匹配的 ID。

PartA
{
    ID: 19,
    name: "Percy",
    taste: "",
    colour: "Blue",
    shape: "",
    same_same: "but different"
}

PartB
{
    ID: 19,
    name: "",
    taste: "Sweet",
    colour: "",
    shape: "Hexagon",
    same_same: "but not the same"
}

我想合并这些以创建以下内容:

Result
{
    ID: 19,
    name: "Percy",
    taste: "Sweet",
    colour: "Blue",
    shape: "Hexagon",
    same_same: "but different"
}

请注意 same_same 的值在每个之间有何不同,但我们认为 PartA 为主,因此结果保留值 但不同

现在让事情复杂化:

假设我们有两个列表:

List<Widget> PartA = getPartA();
List<Widget> PartB = getPartB();

现在这里有一些伪代码描述了我想做的事情:

List<Widget> Result = PartA.MergeWith(PartB).MergeObjectsOn(Widget.ID).toList();

最佳答案

您可以编写自己的扩展方法,如下所示:

static class Extensions
{
    public static IEnumerable<T> MergeWith<T>(this IEnumerable<T> source, IEnumerable<T> other) where T : ICanMerge
    {
        var otherItems = other.ToDictionary(x => x.Key);
        foreach (var item in source)
        {
            yield return (T)item.MergeWith(otherItems[item.Key]);
        }
    }
    public static string AsNullIfEmpty(this string s)
    {
        if (string.IsNullOrEmpty(s))
            return null;
        else
            return s;
    }
}

ICanMerge 是这样的:

public interface ICanMerge
{
    object Key { get; }
    ICanMerge MergeWith(ICanMerge other);
}

实现例如喜欢:

public class Widget : ICanMerge
{
    object ICanMerge.Key { get { return this.ID; } }
    int ID {get;set;}
    string taste {get;set;}
    public ICanMerge MergeWith(ICanMerge other)
    {
        var merged = new Widget();
        var otherWidget = (Widget)other;
        merged.taste = this.taste.AsNullIfEmpty() ?? otherWidget.taste;
        //...
        return merged;
    }
}

那么就很简单了PartA.MergeWith(PartB).ToList()

关于c# - C#合并两个List,将id相同的对象合并为一个列表项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12255487/

相关文章:

c# - Entity Framework 和编译表达式性能

c# - 在这种情况下,编译器真的强制我在密封类中使用 protected 吗?

c# - 我应该在共享主机上加密 web.config 吗?

c# - 为什么 C# 没有为变量和方法设计 'const'?

c# - 如何在 GridView 中实现条件格式

c# - 在 C# (winform .net) 中使用 .c 文件

c# - 会计数据库 - 存储贷方和借方?

c# - 查询 "Memory"的 LINQ

sql - 为什么单独实例化的 Func<T,bool> 谓词不使用 Entity Framework 转换为 SQL?

c# - 两个字符串数组的交集(忽略大小写)