LINQ 设置操作不起作用(相交、除外)

发布于 2024-10-15 00:50:21 字数 692 浏览 7 评论 0原文

我想使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

囚你心 2024-10-22 00:50:21

好吧,它不应该有什么不同,但从对称的角度来看,我会颠倒你创建分配的方式。我还要确保查询仅执行一次,并且其余操作在进程中发生:

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

一种可能性是 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:

var cachedGroups = groups.ToList();
var assigned = cachedGroups.Intersect(user.Groups);
var available = cachedGroups.Except(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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文