0
Class A
{
   string name;
   IList<A> minorList = new List<A>();
}

IList<A> majorList = new List<A>();

I Want to get the instance of A from majorList depending upon the name value, but it is not necessary to have it in the majorList. minorList can also contain the name. How can I get it using Linq. If it is there in only majorList I can get it by using

A a = majorList.First(s => s.Name == "Name");

How about if it is not in the majorList but in some of the List of instance of majorList?

1 Answer 1

3

Sounds like you want something like:

bool ContainsName(A a, string name)
{
    return a.name == name || a.minorList.Any(x => ContainsName(x, name));
}

Then:

A a = majorList.First(x => ContainsName(x, name));

Of course you end up with a problem if there are any cycles in your lists...

Sign up to request clarification or add additional context in comments.

4 Comments

Hi Jon, is this correct one?? A a = majorList.First(x => {return a.name == name || minorList.Any(x => ContainsName(x, name));});
@NiranjanKala: No - you've got to have the method otherwise you can't call it recursively... and if you've got the method, you might as well call it from the lambda expression.
thanks Jon, +1 for resolving my confusion and this nice answer.
Thanks a lot for Jon for the great answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.