Does LINQ work with IEnumerable?

前端 未结 3 1945
走了就别回头了
走了就别回头了 2020-11-30 01:04

I have a class that implements IEnumerable, but doesn\'t implement IEnumerable. I can\'t change this class, and I can\'t use another class

3条回答
  •  感情败类
    2020-11-30 01:45

    You can use Cast() or OfType to get a generic version of an IEnumerable that fully supports LINQ.

    Eg.

    IEnumerable objects = ...;
    IEnumerable strings = objects.Cast();
    

    Or if you don't know what type it contains you can always do:

    IEnumerable e = objects.Cast();
    
    
    

    If your non-generic IEnumerable contains objects of various types and you are only interested in eg. the strings you can do:

    IEnumerable strings = objects.OfType();
    

    提交回复
    热议问题