简体   繁体   English

Linq 找到所有具有特定类型的

[英]Linq find all with certain type

Is there a way to find in a List all items of a certain type with a Linq/Lambda expression?有没有办法用 Linq/Lambda 表达式在列表中找到特定类型的所有项目?

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.就我而言,class 没有任何子类,因此无需考虑 inheritance。

Use OfType<T> like so: 使用OfType<T>像这样:

foreach (var bar in MyList.OfType<Foo>()) {
    ...
}

这样可以吗?

list.Where(t => t is MyType);

Something like this (if using Linq to objects - it won't work with Linq to entities): 这样的事情(如果对对象使用Linq,则对Linq实体不起作用):

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

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))); 我建议使用此var myLst = new List<object>(); var elements = myList.Where(item => item.GetType().IsInstanceOfType(typeof(MyClass))); 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. 您可以使用GetType()方法并与指定的类型进行比较。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM