c# - Linq: find elements with common properties but different types -
i have 2 list objects:
class class1 { public int id { get; set; } public string name { get; set; } public guid uniqueidentifier { get; set; } public bool isvalid { get; set; } } class class2 { public int identifier { get; set; } public string producer{ get; set; } public guid guid { get; set; } public int supplierid { get; set; } }
is there way use linq
elements of type class1
list have same id
(identifier) , guid
elements of type class2
second list?
here 1 way it:
var result = list1 .where(x => list2.any(y => x.id == y.identifier && x.uniqueidentifier == y.guid)) .tolist();
please note version not optimized large lists. if lists small, fine. if have large lists, need solution involves things hashset
s. here example:
var list2hashset = createhashset(list2.select(x => new {x.identifier, x.guid})); var result = list1 .where(x => list2hashset.contains(new {identifier = x.id, guid = x.uniqueidentifier})) .tolist();
where createhashset
defined this:
public static hashset<t> createhashset<t>(ienumerable<t> collection) { return new hashset<t>(collection); }
i had create simple method because compiler complaining cannot resolve correct constructor overload. not sure why.
Comments
Post a Comment