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 e
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)));
I suggest using this
var myLst = new List<object>();
var elements = myList.Where(item => item.GetType().IsInstanceOfType(typeof(MyClass)));
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;
Use OfType<T>
like so:
foreach (var bar in MyList.OfType<Foo>()) {
...
}
Will this do?
list.Where(t => t is MyType);
Something like this (if using Linq to objects - it won't work with Linq to entities):
var specificListOfTypes = from item in list
where item.GetType() == typeof(int)
select item;