使用LINQ在IList中查找项目

Fre*_* LA 9 .net c# linq list

我有一个IList:

IList list = CallMyMethodToGetIList();
Run Code Online (Sandbox Code Playgroud)

我不知道我能得到它的类型

Type entityType = list[0].GetType();`
Run Code Online (Sandbox Code Playgroud)

我想用LINQ搜索这个列表:

var itemFind = list.SingleOrDefault(MyCondition....);
Run Code Online (Sandbox Code Playgroud)

感谢您的任何帮助.

T-m*_*oty 25

简单:

IList list = MyIListMethod();

var item = list
    .Cast<object>()
    .SingleOrDefault(i => i is MyType);
Run Code Online (Sandbox Code Playgroud)

要么:

IList list = MyIListMethod();

var item = list
    .Cast<object>()
    .SingleOrDefault(i => i != null);
Run Code Online (Sandbox Code Playgroud)

希望这个帮助!

  • `OfType <MyType>()`会为你做这个. (5认同)

aba*_*hev 6

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);
Run Code Online (Sandbox Code Playgroud)