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);
Author by
Frenchi In LA
Updated on July 27, 2022Comments
-
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 about 11 years
OfType<MyType>()
will do this for you. -
abatishchev about 11 yearsbasically the are
foreach(item) yield return (T)item
andforeach(item) if (item is T) yield return item as T
respectively. -
Silvermind about 11 yearsI 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 thatdynamic
is not very efficient, but it supports for Linq. -
Silvermind about 11 yearsWhat if the type is a non-nullable value type?
-
T-moty about 11 yearsThe 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 about 11 yearsThe simplest way, in a generic method, like this: link