tags:

views:

93

answers:

5

Is there a way to find in a List all items of a certain type with a Linq/Lambda expression?

Update: Because of the answers, I realize the question wasn't specific enough. I need a new List with only the items of a specific type. In my case, the class hasn't got any subclasses, so no need to take inheritance into account.

+14  A: 

Use OfType<T> like so:

foreach (var bar in MyList.OfType<Foo>()) {
    ...
}
Dave Markle
Using the IEnumerable<T> extension method OfType<T> is the microsoft recommended way of doing this.
devlife
+2  A: 

Will this do?

list.Where(t => t is MyType);
Alex Humphrey
There is a better way.
Dave Markle
Yep, +1 to you Dave.
Alex Humphrey
A: 

maybe you could use ...

        List<object> list = new List<object>();
        list.Add("string");
        list.Add(9);

        var allOfOneType = list.Where(i => i.GetType().Equals(typeof(string)));
hnkz
Yeah ... Dave Markles answer is better -- maybe :)
hnkz
+2  A: 

Something like this:

var specificListOfTypes = from item in list
                            where item.GetType() == typeof(int)
                            select item;
Dave Arkell
A: 

You can use the GetType() method and compare with the specified type.

For instance , I select all values of the string type from the list below:

   var myList = new List<object>();

        myList.Add(5);

        myList.Add("My life");

        var result = from obj in myList
                     where obj.GetType() == typeof(string)
                     select obj;
DrakeVN