LINQ Set Operations not working (Intersect, Except)

倖福魔咒の 提交于 2019-12-08 05:20:54

问题


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...


回答1:


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?



来源:https://stackoverflow.com/questions/4825736/linq-set-operations-not-working-intersect-except

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!