4


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

1
  • 4
    Show your full code.. Commented Apr 8, 2013 at 5:59

1 Answer 1

16

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();
Sign up to request clarification or add additional context in comments.

3 Comments

I am sorry, I forgot to mentiion the List is Dyanamic the List is of Object type. I knows its of type Class A only during runtime
Thanks for your response Marcin, a.FName can't be used - as the List is of Object type, and I will have FName as String.
It can be used after Cast<A>() or OfType<A>, because they both returns IEnumerable<A>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.