Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query in returning Objects from List using LINQ

Tags:

c#

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

like image 581
Arun Selva Kumar Avatar asked Dec 04 '22 11:12

Arun Selva Kumar


1 Answers

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();
like image 134
MarcinJuraszek Avatar answered Dec 25 '22 05:12

MarcinJuraszek