LINQ 设置操作不起作用(相交、除外)
我想使用 LINQ 集合操作的超酷来表达以下内容:
foreach (Group group in groups)
{
if (user.Groups.Contains(group))
{
assignedGroups.Add(group);
}
else
{
availableGroups.Add(group);
}
}
我认为它应该是一个两行代码来实现这一点:
var assigned = user.Groups.Intersect(groups);
var available = groups.Except(user.Groups);
每当我运行这个示例时,foreach 方法都会正确填充我的列表,而集合操作会导致一个空的已分配列表和一个已填充的可用列表。 我认为这一定是关于相等性检查的问题,但 Contains() 正在工作的事实证明这是错误的。 谁能帮我看看我的误解吗?
IEnumerable groups 也是 LINQ 查询的结果,以防万一该信息有帮助......
I'd like to use the Uber-Coolness of LINQ set operations to express the following :
foreach (Group group in groups)
{
if (user.Groups.Contains(group))
{
assignedGroups.Add(group);
}
else
{
availableGroups.Add(group);
}
}
I thought it should be a two-liner achieving this :
var assigned = user.Groups.Intersect(groups);
var available = groups.Except(user.Groups);
Whenever I run this example the foreach approach fills my lists correctly, while the set operations result in an empty assigned list and a filled available list.
I thought it must be a problem concerning the equality check, but the fact that Contains() is working proves this wrong.
Can anyone help me see my misconception here?
the IEnumerable groups is also result of a LINQ query, just in case that information is of some help...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,它不应该有什么不同,但从对称的角度来看,我会颠倒你创建
分配
的方式。我还要确保查询仅执行一次,并且其余操作在进程中发生:一种可能性是
user.Groups
有一个自定义的相等比较器。这可以解释为什么 foreach 版本可以工作而 LINQ 版本却不能。user.Groups
的类型是什么?您对它使用的相等比较器了解多少?Well, it shouldn't make a difference, but from the point of view of symmetry I'd reverse how you're creating
assigned
. I'd also make sure that the query is only executed once, and that the remaining operations occur in-process:One possibility is that
user.Groups
has a custom equality comparer. That would explain why the foreach version worked but the LINQ version didn't. What's the type ofuser.Groups
, and how much do you know about the equality comparer it's using?