合并C#中的两个列表,并将具有相同ID的对象合并到一个列表项中 [英] Merge two Lists in C# and merge objects with the same id into one list item
问题描述
我已经考虑过如何通过推出自己的解决方案来解决此问题,但是我想知道.NET是否已经具有我要实现的功能-如果是的话,我宁愿使用某些功能内置的.
I have already thought about how I'm going to solve this by rolling my own solution, but I wondered if .NET already has the functionality for what I'm trying to acheive - if so, I'd rather use something built-in.
假设我有一个Widget
对象的两个实例,我们称它们为PartA
和PartB
.来自每个服务的信息都来自两个不同的Web服务,但是两个都有匹配的ID.
Suppose I have two instances of a Widget
object, let's call them PartA
and PartB
. The information from each has been garnered from two different web services, but both have matching IDs.
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"
}
我想将它们合并以创建以下内容:
I want to merge these to create the following:
Result
{
ID: 19,
name: "Percy",
taste: "Sweet",
colour: "Blue",
shape: "Hexagon",
same_same: "but different"
}
请注意,same_same
的值在每个之间是如何不同的,但是我们认为PartA是主文件,因此结果保留了值but different
.
Notice how the value for same_same
differs between each, but we consider PartA the master, so the result retains the value but different
.
现在让事情复杂化
假设我们有两个列表:
List<Widget> PartA = getPartA();
List<Widget> PartB = getPartB();
现在,这里有一些伪代码描述了我想做什么:
Now here's some pseudocode describing what I want to do:
List<Widget> Result = PartA.MergeWith(PartB).MergeObjectsOn(Widget.ID).toList();
推荐答案
您可以编写自己的扩展方法,如下所示:
You could write your own extension method(s), something like this:
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#中的两个列表,并将具有相同ID的对象合并到一个列表项中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!