【发布时间】:2013-04-19 01:41:45
【问题描述】:
我浏览了这个网站上的问题,但没有找到与我的特定问题相匹配的问题。
假设我有以下几点:
Product[] store1 = { new Product { Name = "apple", Code = 9, Code1="1" },
new Product { Name = "orange", Code = 4 } };
Product[] store2 = { new Product { Name = "apple", Code = 9, Code2="2" },
new Product { Name = "lemon", Code = 12 } };
与:
public class Product : IEquatable<Product>
{
public string Name { get; set; }
public int Code { get; set; }
public string Code1 { get; set; }
public string Code2 { get; set; }
public bool Equals(Product other)
{
//Check whether the compared object is null.
if (Object.ReferenceEquals(other, null)) return false;
//Check whether the compared object references the same data.
if (Object.ReferenceEquals(this, other)) return true;
//Check whether the products' properties are equal.
return Code.Equals(other.Code) && Name.Equals(other.Name);
}
// If Equals() returns true for a pair of objects
// then GetHashCode() must return the same value for these objects.
public override int GetHashCode()
{
//Get hash code for the Name field if it is not null.
int hashProductName = Name == null ? 0 : Name.GetHashCode();
//Get hash code for the Code field.
int hashProductCode = Code.GetHashCode();
//Calculate the hash code for the product.
return hashProductName ^ hashProductCode;
}
}
如何返回单个 Enumerable,其中 store1 中的数据在匹配时被 store2 中的数据覆盖,并且在不匹配时仅从 store2 插入到 store1 中。基本上,我正在寻找与 TSQL Merge 语句等效的 C#。
在一天结束的时候运行这个:
foreach (var product in union)
Console.WriteLine(product.Name + " " + product.Code + " " + product.Code1 + " " + product.Code2);
我想回来:
苹果 9 1 2
橙色 4
柠檬 12
但是当我运行这个时:
IEnumerable<Product> union = store1.Union(store2);
我明白了:
苹果 9 1
橙色 4
柠檬 12
当我运行这个时:
IEnumerable<Product> union = store1.Concat(store2);
我明白了:
苹果 9 1
橙色 4
苹果 9 2
柠檬 12
提前感谢您的帮助。
【问题讨论】:
-
你要覆盖数据的键值是什么?
-
这只是取自 MSDN 上的 article 的一个例子,但如果我在现实生活中使用这个例子,我喜欢匹配名称和代码,然后覆盖 code1 和 code2,如果他们store1 中为空白。
-
@user1031517 当你有
{ Name = "apple", Code = 9, Code1 = "1" }和{ Name = "apple", Code = 9, Code1 = "2", Code2 = "2" }时会发生什么,在这种情况下应该考虑哪个?这里Code1属性在两个项目中重叠。当我们在两个系列中都有许多这样的重叠产品时会发生什么,那么所有这些都应该被考虑?像{ Name = "apple", Code = 9, Code1 = "1" }和{ Name = "apple", Code = 9, Code2 = "2" }这样的案例是否会出现在同一个集合中,例如,在store1中?
标签: c# linq merge ienumerable