linq对象相等性以及如何正确覆盖它 [英] linq object equality and how to properly override it
本文介绍了linq对象相等性以及如何正确覆盖它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么var excludes = users.Except(matches);
不排除matches
?
如果我希望相等比较器仅使用ID
,正确的方法是什么?例子将不胜感激.
What is the proper way if I want the equality comparer to use only the ID
? Examples would be appreciated.
public class User
{
public int ID { get; set; }
public string Name { get; set; }
public override string ToString()
{
return ID.ToString() + ":" + Name;
}
}
private static void LinqTest2()
{
IEnumerable<User> users = new List<User>
{
new User {ID = 1, Name = "Jack"},
new User {ID = 2, Name = "Tom"},
new User {ID = 3, Name = "Jim"},
new User {ID = 4, Name = "Joe"},
new User {ID = 5, Name = "James"},
new User {ID = 6, Name = "Matt"},
new User {ID = 7, Name = "Jon"},
new User {ID = 8, Name = "Jill"}
}.OfType<User>();
IEnumerable<User> localList = new List<User>
{
new User {ID = 4, Name = "Joe"},
new User {ID = 5, Name = "James"}
}.OfType<User>();
//After creating the two list
var matches = from u in users
join lu in localList
on u.ID equals lu.ID
select lu;
Console.WriteLine("--------------MATCHES----------------");
foreach (var item in matches)
{
Console.WriteLine(item.ToString());
}
Console.WriteLine("--------------EXCLUDES----------------");
var excludes = users.Except(matches);
foreach (var item in excludes)
{
Console.WriteLine(item.ToString());
}
}
推荐答案
sealed class CompareUsersById : IEqualityComparer<User>
{
public bool Equals(User x, User y)
{
if(x == null)
return y == null;
else if(y == null)
return false;
else
return x.ID == y.ID;
}
public int GetHashCode(User obj)
{
return obj.ID;
}
}
然后
var excludes = users.Except(matches, new CompareUsersById());
这篇关于linq对象相等性以及如何正确覆盖它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文