C# 使用 LINQ 在 IList 中查找项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15281311/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 16:16:19 来源:igfitidea点击:
Find item in IList with LINQ
提问by Frenchi In LA
I have an IList:
我有一个 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:
我想用 LINQ 搜索这个列表,例如:
var itemFind = list.SingleOrDefault(MyCondition....);
Thank you for any help.
感谢您的任何帮助。
采纳答案by T-moty
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!
希望这有帮助!
回答by Silvermind
As Jakob M?ll?s says you could use dynamic. At least it works in LinqPad:
正如 Jakob M?ll?s 所说,您可以使用动态。至少它适用于 LinqPad:
IList list = new List<string>();
list.Add("TEST");
list.Add("NOT");
Console.WriteLine(list.Cast<dynamic>().FirstOrDefault(l => l== "NOT"));
回答by abatishchev
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);