c# - LINQ look up list of objs in datable of different objs that share a common property -
i have list obj , list b obj b. both list share 1 property , want obj b of list b has in , pull them out.
so, ex.
list bunch of people
list b bunch of names
both list have personid
now want people names in list b. thinking a:
class names { public int id {get;set;} public string name {get;set;} } class people { public int id {get;set;} public string name {get;set;} } var newlist = new list<person>(); foreach(var n in names) { var person = people.firstordefault(p => p.name == n); if(person!=null) { newlist.add(person); } } }
i wondering there more efficent way linq can because wont list everytime might database im calling , dont want call database thousands no reason.
this bad example if think it.
this codes :
var newlist = new list<person>(); foreach(var n in names) { var person = people.firstordefault(p => p.name == n); if(person!=null) { newlist.add(person); } }
will produce same result :
var newlist = new list<person>(); newlist = people.where(p => names.contains(p.name)).tolist();
responding update, if names
list of names
object instead of string, can follow :
newlist = people.where(p => names.select(o => o.name).contains(p.name)).tolist();
Comments
Post a Comment