Arun Selva Kumar
Arun Selva Kumar

Reputation: 2732

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). I need to get the list of datas whose LName is "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

Upvotes: 4

Views: 33068

Answers (1)

MarcinJuraszek
MarcinJuraszek

Reputation: 125610

It can be easily done using 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<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):

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

Upvotes: 16

Related Questions