3

In C#, if I have multiple List<T> lists, where each item in the list inherits from an interface that has an id property, how is the best way to retrieve an object that has a specific id?

All ids are unique and all lists are stored in one object.

I am currently thinking of writing a Find piece of code, for each list, and if the object returned is not null, then the object returned is the object with the id.

Is there a better way to do this?

Just to inform, this question is about how to find an object in multiple lists, rather than the code to find an object in a single list.

2

4 Answers 4

3

How about using Linq:

var result = list.First(x => x.id == findThisId);
Sign up to request clarification or add additional context in comments.

Comments

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

You also could treat the multiple lists as one concatenated list:

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

Comments

0

You can create a list of lists, and search it using LINQ's SelectMany:

Here is an example setup:

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 is the 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 is a list that contains lists of different subtypes of IId. It needs to be declared as list of IEnumerables because of covariance rules for generics.

Now you can search all by Id, like this:

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

Demo.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.