Does LINQ work with IEnumerable?

前端 未结 3 1911
走了就别回头了
走了就别回头了 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:43

    Yes it can. You just need to use the Cast<T> function to get it converted to a typed IEnumerable<T>. For example:

    IEnumerable e = ...;
    IEnumerable<object> e2 = e.Cast<object>();
    

    Now e2 is an IEnumerable<T> and can work with all LINQ functions.

    0 讨论(0)
  • 2020-11-30 01:45

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

    Eg.

    IEnumerable objects = ...;
    IEnumerable<string> strings = objects.Cast<string>();
    

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

    IEnumerable<object> e = objects.Cast<object>();
    

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

    IEnumerable<string> strings = objects.OfType<string>();
    
    0 讨论(0)
  • 2020-11-30 01:47

    You can also use LINQ's query comprehension syntax, which casts to the type of the range variable (item in this example) if a type is specified:

    IEnumerable list = new ArrayList { "dog", "cat" };
    
    IEnumerable<string> result =
      from string item in list
      select item;
    
    foreach (string s in result)
    {
        // InvalidCastException at runtime if element is not a string
    
        Console.WriteLine(s);
    }
    

    The effect is identical to @JaredPar's solution; see 7.16.2.2: Explicit Range Variable Types in the C# language specification for details.

    0 讨论(0)
提交回复
热议问题