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 ienumerables because of covariance rules generics.

now can search all id, this:

var item5 = all.selectmany(list => list).firstordefault(item => item.id == 5); 

demo.


Comments

Popular posts from this blog

javascript - Karma not able to start PhantomJS on Windows - Error: spawn UNKNOWN -

c# - Display ASPX Popup control in RowDeleteing Event (ASPX Gridview) -

Nuget pack csproj using nuspec -