我有两个对象列表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}
答案 0 :(得分:2)
产生预期键的完整样本: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
key:4
答案 1 :(得分:1)
这会产生您的预期输出:
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}