简体   繁体   English

查询使用LINQ从List返回对象

[英]Query in returning Objects from List using LINQ


I have a List Say foo, which holds data of type Class A (containing members FName, LName, Total). 我有一个List Say foo,它包含类A类型的数据(包含成员FName,LName,Total)。 I need to get the list of datas whose LName is "foobar". 我需要获取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. 编辑:我很抱歉Geeks,列表是Dyanamic列表是对象类型。 I knows its of type Class A only during runtime 我只在运行时知道它的类型A.

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. 对于List<object>使用Cast<T>扩展方法。 It will cast all source collection elements into A (and throw exception when it's not possible): 它会将所有源集合元素强制转换为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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM