Linq find all with certain type

后端 未结 6 1562
离开以前
离开以前 2021-01-03 18:01

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

相关标签:
6条回答
  • 2021-01-03 18:31

    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)));
    
    0 讨论(0)
  • 2021-01-03 18:31

    I suggest using this var myLst = new List<object>(); var elements = myList.Where(item => item.GetType().IsInstanceOfType(typeof(MyClass)));

    0 讨论(0)
  • 2021-01-03 18:34

    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;
    
    0 讨论(0)
  • 2021-01-03 18:35

    Use OfType<T> like so:

    foreach (var bar in MyList.OfType<Foo>()) {
        ...
    }
    
    0 讨论(0)
  • 2021-01-03 18:37

    Will this do?

    list.Where(t => t is MyType);
    
    0 讨论(0)
  • 2021-01-03 18:41

    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;
    
    0 讨论(0)
提交回复
热议问题