我已经考虑过如何通过推出我自己的解决方案来解决这个问题,但我想知道 .NET 是否已经具备我想要实现的功能 - 如果是这样,我宁愿使用一些东西内置。
假设我有一个 Widget
对象的两个实例,我们称它们为 PartA
和 PartB
。每个人的信息都是从两个不同的网络服务中获取的,但两者都有匹配的 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/