开发者

LINQ without IEqualityComparer implementation

I have 2 collection with different classes. MyClass1 - Name,Age,etc M开发者_如何学编程yClass2 - Nick, Age, etc

I want to find except of this collections. Something like

list1.Exept(list2, (l1,l2) => l1.Name==l2.Nick);

But i cannt write this code and need to implement my own comparer class with IEqualityComparer interface and it's looking very overhead for this small task. Is there any elegant solution?


Except really doesn't work with two different sequence types. I suggest that instead, you use something like:

var excludedNicks = new HashSet<string>(list2.Select(x => x.Nick));
var query = list1.Where(x => !excludedNicks.Contains(x.Name));

(Note that this won't perform the "distinct" aspect of Except. If you need that, please say so and we can work out what you need.)


Well, build a set of all the nicknames, then run against that.

var nicknames = new HashSet<string>(list2.Select(l2 => l2.Nick));
var newNames = from l1 in list1
               where !nicknames.Contains(l1.Name)
               select l1;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜