用Linq覆盖/加入两个集合 [英] Overlay/Join two collections with Linq
问题描述
我有以下情况:
列表1有20个类型的项目,列表2有5个相同类型的项目。列表1已经包含来自列表2的项目,但处于不同的状态。我想用列表2中的项目覆盖列表1中的5个项目。
List 1 has 20 items of type TItem, List 2 has 5 items of the same type. List 1 already contains the items from List 2 but in a different state. I want to overwrite the 5 items in List 1 with the items from List 2.
我认为连接可能会工作,但是我想覆盖列表1中的项目,
I thought a join might work, but I want to overwrite the items in List 1, not join them together and have duplicates.
有一个唯一的键,可用于在List 1中找到要覆盖的项目,键类型为int
There is a unique key that can be used to find which items to overwrite in List 1 the key is of type int
推荐答案
您可以使用内置的Linq .Except(),但它想要一个IEqualityComparer,所以使用 .Except()的流畅版本。
You could use the built in Linq .Except() but it wants an IEqualityComparer so use a fluid version of .Except() instead.
假设一个对象带有整数键,如下所示:
Assuming an object with an integer key as you indicated:
public class Item
{
public int Key { get; set; }
public int Value { get; set; }
public override string ToString()
{
return String.Format("{{{0}:{1}}}", Key, Value);
}
}
对象的原始列表可以与已更改的一个如下:
The original list of objects can be merged with the changed one as follows:
IEnumerable<Item> original = new[] { 1, 2, 3, 4, 5 }.Select(x => new Item
{
Key = x,
Value = x
});
IEnumerable<Item> changed = new[] { 2, 3, 5 }.Select(x => new Item
{
Key = x,
Value = x * x
});
IEnumerable<Item> result = original.Except(changed, x => x.Key).Concat(changed);
result.ForEach(Console.WriteLine);
输出:
{1:1}
{4:4}
{2:4}
{3:9}
{5:25}
这篇关于用Linq覆盖/加入两个集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!