开发者

LINQ Set Operations not working (Intersect, Except)

开发者 https://www.devze.com 2023-02-07 00:29 出处:网络
I\'d like to use the Uber-Coolness of LINQ set operations to express the following : foreach (Group group in groups)

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


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?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号