查找并选择两个对象列表之间的特定更改
本文关键字:之间 列表 对象 两个 选择 查找 | 更新日期: 2023-09-27 17:57:44
我有两个对象T的列表。每个T都有唯一的密钥"T.key"
List<T> List1;
List<T> List2;
我想创建一个列表,列出只在List2中的所有对象的键,也列出两个列表中但有特定属性差异的对象的键(让我们将它们命名为T.a和T.b)。此外,列表内容的顺序不一定相同。
示例输入/输出:
List1 = {{key:1,a:10,b:10,c:10}, {key:2,a:10,b:10,c:10}, {key:3,a:10,b:10,c:10}}
List2 = {{key:1,a:10,b:10,c:99}, {key:2,a:11,b:10,c:10}, {key:4,a:10,b:10,c:10}}
Result = {2,4}
一个完整的样本,它产生预期的密钥:2和4
List<F> L1 = new List<F>{new F(1,10,10,10), new F(2,10,10,10), new F(3,10,10,10)};
List<F> L2 = new List<F>{new F(1,10,10,99), new F(2,11,10,10), new F(4,10,10,10)};
void Main() { // Client code. One call covers the biz logic (and sample output)
// Must call Except on L2 with L1 as the arg for proper eval of biz logic
foreach ( var item in L2.Except(L1, new CompareListsOfObjsF()) )
Console.WriteLine("key: " + item.key);
}
class F { // Quick, dirty sample POCO w/ constructor
public int key, a, b, c;
public F(int mk, int ma, int mb, int mc) { key=mk; a=ma; b=mb; c=mc; }
}
class CompareListsOfObjsF : IEqualityComparer<F> {
// business-specific equality logic - notice that 'c' is not evaluated
public bool Equals(F x, F y) {
return x.key == y.key && x.a == y.a && x.b == y.b;
}
// The logic will not work without a proper hash function:
public int GetHashCode(F x) { unchecked { // Overflow is ok
int h = 17 * 23 + x.key;
h += h * 23 + x.a;
h += h * 23 + x.b;
return h; // c has to be left out for selection biz logic to work
}
}
}
输出:
密钥:2
密钥:4
这将产生您期望的输出:
List<T> list1 = new List<T> { new T { key = 1, a = 10, b = 10, c = 10 }, new T { key = 2, a = 10, b = 10, c = 10 }, new T { key = 3, a = 10, b = 10, c = 10 } };
List<T> list2 = new List<T> { new T { key = 1, a = 10, b = 10, c = 99 }, new T { key = 2, a = 11, b = 10, c = 10 }, new T { key = 4, a = 10, b = 10, c = 10 } };
List<int> difference = new List<int>();
foreach (var item2 in list2)
{
var item1 = list1.FirstOrDefault(i => i.key == item2.key);
if (item1 != null)
{
if (item2.a == item1.a && item2.b == item1.b)
continue;
}
difference.Add(item2.key);
}
difference
包含{2,4}