Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I use LINQ to Objects when my class implements IEnumerable<T> multiple times?

I have an interesting issue where a class inherits from a class that implements IEnumerable, but I also want the class to implement IEnumerable for a different type. Everything works except for IEnumerable extension methods, which means I can't do any LINQ to objects by default without always having to cast first. Does anyone have any ideas besides constantly casting?

using System;
using System.Collections.Generic;
using System.Linq;

namespace LinqTesting
{
    public class Trucks<T> : Vehicles, IEnumerable<Truck>
    {    
        public Trucks()
        {    
            // Does Compile
            var a = ((IEnumerable<Truck>)this).FirstOrDefault();
            // Doesn't Compile, Linq.FirstOrDefault not found
            var b = this.FirstOrDefault();
        }    

        public new IEnumerator<Truck> GetEnumerator() { throw new NotImplementedException(); }
    }    

    public class Vehicles : IEnumerable<Vehicle>
    {    
        public IEnumerator<Vehicle> GetEnumerator() { throw new NotImplementedException(); }
        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw new NotImplementedException(); }
    }    

    public class Vehicle { }

    public class Truck : Vehicle { }
}     
like image 539
Daryl Avatar asked Jun 24 '11 19:06

Daryl


People also ask

Can you use Linq on IEnumerable?

All LINQ methods are extension methods to the IEnumerable<T> interface. That means that you can call any LINQ method on any object that implements IEnumerable<T> . You can even create your own classes that implement IEnumerable<T> , and those classes will instantly "inherit" all LINQ functionality!

What is IEnumerable t in c#?

IEnumerable interface is a generic interface which allows looping over generic or non-generic lists. IEnumerable interface also works with linq query expression. IEnumerable interface Returns an enumerator that iterates through the collection.

What is IEnumerable in Visual basic?

The IEnumerable<T> interface is implemented by classes that can return a sequence of values one item at a time. The advantage of returning data one item at a time is that you do not have to load the complete set of data into memory to work with it.


1 Answers

Actually you can, but you can't take the advantage of generic types inference, because your class implements two IEnumerable<T> of two different types and the compiler can't know which type you want to use.

You can specify it direclty, like:

var b = this.FirstOrDefault<Truck>();
like image 160
digEmAll Avatar answered Dec 16 '22 21:12

digEmAll