c# - Get an object from multiple List<T> lists with a specific id -
in c#
, if have multiple list<t>
lists, each item in list inherits interface has id
property, how best way retrieve object has specific id
?
all ids
unique , lists stored in 1 object.
i thinking of writing find
piece of code, each list, , if object returned not null, object returned object id.
is there better way this?
just inform, question how find object in multiple lists, rather code find object in single list.
you can create list of lists, , search using linq's selectmany
:
here example setup:
interface iid { int id {get;} } class : iid { public int id {get;set;} public override string tostring() { return "a"+id; } } class b : iid { public int id {get;set;} public override string tostring() { return "b"+id; } }
iid
common interface implemented a
, b
. can this:
var = new list<a> {new {id=5}, new {id=6}}; var b = new list<b> {new b {id=7}, new b {id=8}}; var = new list<ienumerable<iid>> {a, b};
all
list contains lists of different subtypes of iid
. needs declared list of ienumerable
s because of covariance rules generics.
now can search all
id
, this:
var item5 = all.selectmany(list => list).firstordefault(item => item.id == 5);
Comments
Post a Comment