Find item in IList with LINQ

48,324

Solution 1

Simple:

IList list = MyIListMethod();

var item = list
    .Cast<object>()
    .SingleOrDefault(i => i is MyType);

or:

IList list = MyIListMethod();

var item = list
    .Cast<object>()
    .SingleOrDefault(i => i != null);

hope this help!

Solution 2

IList list = ...

// if all items are of given type
IEnumerable<YourType> seq = list.Cast<YourType>().Where(condition);

// if only some of them    
IEnumerable<YourType> seq = list.OfType<YourType>().Where(condition);
Share:
48,324
Frenchi In LA
Author by

Frenchi In LA

Updated on July 27, 2022

Comments

  • Frenchi In LA
    Frenchi In LA almost 2 years

    I have an IList:

    IList list = CallMyMethodToGetIList();
    

    that I don't know the type I can get it

    Type entityType = list[0].GetType();`
    

    I would like to search this list with LINQ something like:

    var itemFind = list.SingleOrDefault(MyCondition....);
    

    Thank you for any help.

  • abatishchev
    abatishchev about 11 years
    OfType<MyType>() will do this for you.
  • abatishchev
    abatishchev about 11 years
    basically the are foreach(item) yield return (T)item and foreach(item) if (item is T) yield return item as T respectively.
  • Silvermind
    Silvermind about 11 years
    I was under the impression the type was not known at compile time since he used list[0].GetType() to get the type. I agree with your comment at my answer that dynamic is not very efficient, but it supports for Linq.
  • Silvermind
    Silvermind about 11 years
    What if the type is a non-nullable value type?
  • T-moty
    T-moty about 11 years
    The filters in .SingleOrDefault(xxx) are ONLY for example. I mean the .Cast<object>() method. ...but your question is interesting! Give me some mins...
  • T-moty
    T-moty about 11 years
    The simplest way, in a generic method, like this: link