Get an object from multiple lists List <T> with a specific id

Q C#

, if I have multiple lists List<T>

, where each item in the list inherits from an interface that has a property id

, what's the best way to get an object that has a specific one id

?

All are ids

unique and all lists are stored in one object.

I am currently thinking about writing code Find

for each list and if the returned object is not null then the returned object is an object with an ID.

Is there a better way to do this?

To communicate, this question is about how to find an object in multiple lists, not the code for finding an object in one list.

+3


source to share


4 answers


You can create a list of lists and search using LINQ SelectMany

:

Here's an example installation:

interface IId {
    int Id {get;}
}
class A : 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

- a common interface implemented by A

and B

. Now you can do this:

var a = new List<A> {new A {Id=5}, new A {Id=6}};
var b = new List<B> {new B {Id=7}, new B {Id=8}};
var all = new List<IEnumerable<IId>> {a, b};

      



all

- a list containing lists of different subtypes IId

. It has to be declared as a list IEnumerable

due to generic covariance rules.

Now you can search all

for Id

, for example:

var item5 = all.SelectMany(list => list).FirstOrDefault(item => item.Id == 5);

      

Demo version

0


source


How about using Linq:



var result = list.First(x => x.id == findThisId);

      

+3


source


var result =
 new [] { list1, list2, list3, ... }
 .Select(list => list.FirstOrDefault(x => x.id == findThisId))
 .First(x => x != null);

      

You can also treat multiple lists as one concatenated list:

var result =
 new [] { list1, list2, list3, ... }
 .SelectMany(x => x) //flatten
 .FirstOrDefault(x => x.id == findThisId);

      

+1


source


var result = list.Where(i => i.Id == id).FirstOrDefault();

      

0


source







All Articles