LINQ selection by type of an object

我怕爱的太早我们不能终老 提交于 2019-12-20 10:58:48

问题


I have a collection which contains two type of objects A & B.

Class Base{}
Class A : Base {}
Class B : Base {}

List<Base> collection = new List<Base>();
collection.Add(new A());
collection.Add(new B());
collection.Add(new A());
collection.Add(new A());
collection.Add(new B());

Now I want to select the objects from the collection based on its type (A or B, not both).

How I can write a LINQ query for this? Please help me. Otherwise I need to loop through the collection, which I dont want to. Thanks.

Edit:

Thank you all for your help. Now I can use OfType() from LINQ. But I think in my case it wont work. My situation is

Class Container
{
  List<Base> bases;
}

List<Container> containers = new List<Container>();

Now I want to select the container from containers, which has at least one type A. May be this cant be done by LINQ. Thanks a lot.


回答1:


You can use the OfType Linq method for that:

var ofTypeA = collection.OfType<A>();

Regarding your unwillingness to loop throught the collection, you should keep in mind that Linq does not do magic tricks; I didn't check the implementation of OfType, but I would be surprised not to find a loop or iterator in there.




回答2:


You can use the OfType extension method for this

IEnumerable<A> filteredToA = list.OfType<A>();
IEnumerable<B> filteredToB = list.OfType<B>();



回答3:


For completeness, here is the source code of Enumerable.OfType<T>.

public static IEnumerable<TResult> OfType<TResult>(this IEnumerable source) {
    if (source == null) throw Error.ArgumentNull("source"); 
    return OfTypeIterator<TResult>(source); 
}

static IEnumerable<TResult> OfTypeIterator<TResult>(IEnumerable source) {
    foreach (object obj in source) {
        if (obj is TResult) yield return (TResult)obj;
    } 
}

You can see that it lazily evaluates the source stream.



来源:https://stackoverflow.com/questions/3842714/linq-selection-by-type-of-an-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!