LINQ Set操作不起作用(相交,除外) [英] LINQ Set Operations not working (Intersect, Except)

查看:148
本文介绍了LINQ Set操作不起作用(相交,除外)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用LINQ set操作的Uber-Coolness来表达以下内容:

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);

每当我运行此示例时,foreach方法都会正确填充我的列表,而set操作会导致分配的列表为空,并且可用列表已填充. 我以为关于相等性检查一定是一个问题,但是 Contains()起作用的事实证明了这是错误的. 有人可以帮我看看我的误解吗?

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?

IEnumerable 也是LINQ查询的结果,以防万一信息有帮助...

the IEnumerable groups is also result of a LINQ query, just in case that information is of some help...

推荐答案

好吧,不应该有所作为,但是从对称性的角度来看,我改变了你的方式创建assigned.我还要确保查询仅执行一次,其余操作在进程内进行:

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:

var cachedGroups = groups.ToList();
var assigned = cachedGroups.Intersect(user.Groups);
var available = cachedGroups.Except(user.Groups);

一种可能性是user.Groups具有自定义的相等比较器. 解释为什么foreach版本有效,而LINQ版本无效. user.Groups是什么类型,您对它使用的相等比较器了解多少?

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 of user.Groups, and how much do you know about the equality comparer it's using?

这篇关于LINQ Set操作不起作用(相交,除外)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆