C# 使用 LINQ 从列表中返回对象的查询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15872217/
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 18:13:52  来源:igfitidea点击:

Query in returning Objects from List using LINQ

c#linq

提问by Arun Selva Kumar


I have a List Say foo, which holds data of type Class A (containing members FName, LName, Total). I need to get the list of datas whose LName is "foobar".


我有一个 List Say foo,它包含 A 类数据(包含成员 FName、LName、Total)。我需要获取 LName 为“foobar”的数据列表。

I know this sounds a simple question, but this pisses me off! because the I will get the Members for returning the list in runtime.

我知道这听起来很简单,但这让我很生气!因为我将获得在运行时返回列表的成员。

Thanks in advance

提前致谢

EDIT : I am sorry Geeks, the List is Dyanamic the List is of Object type. I knows its of type Class A only during runtime

编辑:对不起,极客,列表是动态的,列表是对象类型的。我只在运行时知道它的 A 类类型

采纳答案by MarcinJuraszek

It can be easily done using LINQ:

使用 LINQ 可以轻松完成:

using System.Linq;

(...)

List<A> foo = GetFooList();    // gets data
List<A> fooBorItems = foo.Where(a = > a.FName == "foobar").ToList();

Or using syntax based query:

或者使用基于语法的查询:

List<A> fooBorItems = (from a in foo
                       where a.FName == "foobar"
                       select a).ToList();

For List<object>use Cast<T>extension method first. It will cast all source collection elements into A(and throw exception when it's not possible):

对于List<object>使用Cast<T>扩展方法第一。它将所有源集合元素转换为A(并在不可能时抛出异常):

List<A> fooBorItems = foo.Cast<A>().Where(a = > a.FName == "foobar").ToList();

or OfType<A>(which will return only elements that can be casted, without exceptions for these that can't):

OfType<A>(将只返回可以转换的元素,不能转换的元素也不例外):

List<A> fooBorItems = foo.OfType<A>().Where(a = > a.FName == "foobar").ToList();