C# LINQ 运算符和对象相等除外
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/693324/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
LINQ Except operator and object equality
提问by Abhijeet Patel
Here is an interesting issue I noticed when using the Except
Operator:
I have list of users from which I want to exclude some users:
这是我在使用Except
Operator时注意到的一个有趣问题:我有一个用户列表,我想从中排除一些用户:
The list of users is coming from an XML file:
用户列表来自 XML 文件:
The code goes like this:
代码是这样的:
interface IUser
{
int ID { get; set; }
string Name { get; set; }
}
class User: IUser
{
#region IUser Members
public int ID
{
get;
set;
}
public string Name
{
get;
set;
}
#endregion
public override string ToString()
{
return ID + ":" +Name;
}
public static IEnumerable<IUser> GetMatchingUsers(IEnumerable<IUser> users)
{
IEnumerable<IUser> localList = new List<User>
{
new User{ ID=4, Name="James"},
new User{ ID=5, Name="Tom"}
}.OfType<IUser>();
var matches = from u in users
join lu in localList
on u.ID equals lu.ID
select u;
return matches;
}
}
class Program
{
static void Main(string[] args)
{
XDocument doc = XDocument.Load("Users.xml");
IEnumerable<IUser> users = doc.Element("Users").Elements("User").Select
(u => new User
{ ID = (int)u.Attribute("id"),
Name = (string)u.Attribute("name")
}
).OfType<IUser>(); //still a query, objects have not been materialized
var matches = User.GetMatchingUsers(users);
var excludes = users.Except(matches); // excludes should contain 6 users but here it contains 8 users
}
}
When I call User.GetMatchingUsers(users)
I get 2 matches as expected.
The issue is that when I call users.Except(matches)
The matching users are not being excluded at all! I am expecting 6 users ut "excludes" contains all 8 users instead.
当我打电话时,User.GetMatchingUsers(users)
我按预期获得了 2 场比赛。问题是,当我调用users.Except(matches)
匹配的用户时,根本没有被排除!我期待 6 个用户 ut“排除”包含所有 8 个用户。
Since all I'm doing in GetMatchingUsers(IEnumerable<IUser> users)
is taking the IEnumerable<IUser>
and just returning
the IUsers
whose ID's match( 2 IUsers in this case), my understanding is that by default Except
will use reference equality
for comparing the objects to be excluded. Is this not how Except
behaves?
由于我所做的 GetMatchingUsers(IEnumerable<IUser> users)
只是获取IEnumerable<IUser>
并返回IUsers
其 ID 的匹配项(在本例中为 2 个 IUsers),因此我的理解是默认情况下Except
将使用引用相等性来比较要排除的对象。这不是Except
行为方式吗?
What is even more interesting is that if I materialize the objects using .ToList()
and then get the matching users, and call Except
,
everything works as expected!
更有趣的是,如果我使用对象来实现对象.ToList()
,然后获取匹配的用户,然后调用Except
,一切都会按预期进行!
Like so:
像这样:
IEnumerable<IUser> users = doc.Element("Users").Elements("User").Select
(u => new User
{ ID = (int)u.Attribute("id"),
Name = (string)u.Attribute("name")
}
).OfType<IUser>().ToList(); //explicity materializing all objects by calling ToList()
var matches = User.GetMatchingUsers(users);
var excludes = users.Except(matches); // excludes now contains 6 users as expected
I don't see why I should need to materialize objects for calling Except
given that its defined on IEnumerable<T>
?
我不明白为什么我需要具体化对象以进行调用,Except
因为它定义在IEnumerable<T>
?
Any suggesstions / insights would be much appreciated.
任何建议/见解将不胜感激。
采纳答案by Jeff Yates
I think I know why this fails to work as expected. Because the initial user list is a LINQ expression, it is re-evaluated each time it is iterated (once when used in GetMatchingUsers
and again when doing the Except
operation) and so, new user objects are created. This would lead to different references and so no matches. Using ToList
fixes this because it iterates the LINQ query once only and so the references are fixed.
我想我知道为什么这无法按预期工作。由于初始用户列表是一个 LINQ 表达式,因此每次迭代时都会对其进行重新评估(GetMatchingUsers
在执行Except
操作时使用一次,在执行操作时再次评估),因此会创建新的用户对象。这将导致不同的引用,因此没有匹配。UsingToList
修复了这个问题,因为它只迭代 LINQ 查询一次,因此引用是固定的。
I've been able to reproduce the problem you have and having investigated the code, this seems like a very plausible explanation. I haven't proved it yet, though.
我已经能够重现您遇到的问题并调查了代码,这似乎是一个非常合理的解释。不过我还没有证明。
Update
I just ran the test but outputting the users
collection before the call to GetMatchingUsers
, in that call, and after it. Each time the hash code for the object was output and they do indeed have different values each time indicating new objects, as I suspected.
更新
我刚刚运行了测试,但users
在调用之前GetMatchingUsers
、调用中和调用之后输出了集合。每次输出对象的哈希码时,它们确实有不同的值,每次指示新对象时,正如我所怀疑的那样。
Here is the output for each of the calls:
这是每个调用的输出:
==> Start
ID=1, Name=Jeff, HashCode=39086322
ID=2, Name=Alastair, HashCode=36181605
ID=3, Name=Anthony, HashCode=28068188
ID=4, Name=James, HashCode=33163964
ID=5, Name=Tom, HashCode=14421545
ID=6, Name=David, HashCode=35567111
<== End
==> Start
ID=1, Name=Jeff, HashCode=65066874
ID=2, Name=Alastair, HashCode=34160229
ID=3, Name=Anthony, HashCode=63238509
ID=4, Name=James, HashCode=11679222
ID=5, Name=Tom, HashCode=35410979
ID=6, Name=David, HashCode=57416410
<== End
==> Start
ID=1, Name=Jeff, HashCode=61940669
ID=2, Name=Alastair, HashCode=15193904
ID=3, Name=Anthony, HashCode=6303833
ID=4, Name=James, HashCode=40452378
ID=5, Name=Tom, HashCode=36009496
ID=6, Name=David, HashCode=19634871
<== End
And, here is the modified code to show the problem:
而且,这是显示问题的修改后的代码:
using System.Xml.Linq;
using System.Collections.Generic;
using System.Linq;
using System;
interface IUser
{
int ID
{
get;
set;
}
string Name
{
get;
set;
}
}
class User : IUser
{
#region IUser Members
public int ID
{
get;
set;
}
public string Name
{
get;
set;
}
#endregion
public override string ToString()
{
return ID + ":" + Name;
}
public static IEnumerable<IUser> GetMatchingUsers(IEnumerable<IUser> users)
{
IEnumerable<IUser> localList = new List<User>
{
new User{ ID=4, Name="James"},
new User{ ID=5, Name="Tom"}
}.OfType<IUser>();
OutputUsers(users);
var matches = from u in users
join lu in localList
on u.ID equals lu.ID
select u;
return matches;
}
public static void OutputUsers(IEnumerable<IUser> users)
{
Console.WriteLine("==> Start");
foreach (IUser user in users)
{
Console.WriteLine("ID=" + user.ID.ToString() + ", Name=" + user.Name + ", HashCode=" + user.GetHashCode().ToString());
}
Console.WriteLine("<== End");
}
}
class Program
{
static void Main(string[] args)
{
XDocument doc = new XDocument(
new XElement(
"Users",
new XElement("User", new XAttribute("id", "1"), new XAttribute("name", "Jeff")),
new XElement("User", new XAttribute("id", "2"), new XAttribute("name", "Alastair")),
new XElement("User", new XAttribute("id", "3"), new XAttribute("name", "Anthony")),
new XElement("User", new XAttribute("id", "4"), new XAttribute("name", "James")),
new XElement("User", new XAttribute("id", "5"), new XAttribute("name", "Tom")),
new XElement("User", new XAttribute("id", "6"), new XAttribute("name", "David"))));
IEnumerable<IUser> users = doc.Element("Users").Elements("User").Select
(u => new User
{
ID = (int)u.Attribute("id"),
Name = (string)u.Attribute("name")
}
).OfType<IUser>(); //still a query, objects have not been materialized
User.OutputUsers(users);
var matches = User.GetMatchingUsers(users);
User.OutputUsers(users);
var excludes = users.Except(matches); // excludes should contain 6 users but here it contains 8 users
}
}
回答by CMS
I think you should implement IEquatable<T>to provide your own Equals and GetHashCode methods.
我认为你应该实现IEquatable<T>来提供你自己的 Equals 和 GetHashCode 方法。
From MSDN (Enumerable.Except):
来自 MSDN ( Enumerable.Except):
If you want to compare sequences of objects of some custom data type, you have to implement the IEqualityComparer<(Of <(T>)>) generic interface in your class. The following code example shows how to implement this interface in a custom data type and provide GetHashCode and Equals methods.
如果要比较某些自定义数据类型的对象序列,则必须在类中实现 IEqualityComparer<(Of <(T>)>) 通用接口。下面的代码示例演示如何在自定义数据类型中实现此接口并提供 GetHashCode 和 Equals 方法。
回答by Anton Tolmachev
a) You need to override GetHashCode function. It MUST return equal values for equal IUser objects. For example:
a) 您需要覆盖 GetHashCode 函数。它必须为相等的 IUser 对象返回相等的值。例如:
public override int GetHashCode()
{
return ID.GetHashCode() ^ Name.GetHashCode();
}
b) You need to override object.Equals(object obj) function in classes that implement IUser.
b) 您需要在实现 IUser 的类中覆盖 object.Equals(object obj) 函数。
public override bool Equals(object obj)
{
IUser other = obj as IUser;
if (object.ReferenceEquals(obj, null)) // return false if obj is null OR if obj doesn't implement IUser
return false;
return (this.ID == other.ID) && (this.Name == other.Name);
}
c) As an alternative to (b)IUser may inherit IEquatable:
c) 作为(b)的替代方案,IUser 可以继承 IEquatable:
interface IUser : IEquatable<IUser>
...
User class will need to provide bool Equals(IUser other) method in that case.
在这种情况下,用户类将需要提供 bool Equals(IUser other) 方法。
That's all. Now it works without calling .ToList() method.
就这样。现在它无需调用 .ToList() 方法即可工作。