David Klempfner
David Klempfner

Reputation: 9870

Replacing var with type name in Linq query

I have the following code:

List<string> myCars = new List<string>()
    { "Mercury Cougar", "Dodge Dart", "Ford Taurus SHO",
      "Dodge Charger", "Chevrolet Blazer", "Dodge Neon" };

    var dodges = from someCars in myCars
                 where someCars.Contains("Dodge")
                 orderby someCars descending
                 select someCars;

Console.WriteLine(dodges.GetType()); //System.Linq.OrderedEnumerable`2[System.String,System.String]

dodges.GetType() returns the fully qualified name in CIL syntax.

If I translate it to C# and use it to replace var, it doesn't compile:

The type or namespace name 'OrderedEnumerable<,>' does not exist in the namespace 'System.Linq' (are you missing an assembly reference?)

System.Linq.OrderedEnumerable<string, string> dodges = from someCars in myCars
                         where someCars.Contains("Dodge")
                         orderby someCars descending
                         select someCars;

This is because the OrderedEnumerable<string, string> is not available, only System.Linq.IOrderedEnumerable<string> is available.

Why is OrderedEnumerable<string, string> not available?

Upvotes: 2

Views: 277

Answers (1)

xanatos
xanatos

Reputation: 111820

Why is OrderedEnumerable<string, string> not available

Because it is an "internal" impementation of the interface. There is no reason why it should be available or documented. With LINQ you should program against interfaces (IEnumerable<>, IOrderedEnumerable<>, IQueryable<>...)

If you take a look, all the LINQ methods return an internal class that derives from one of those interfaces, and often they can return instances of multiple different classes, depending on the input. For example the Enumerable.Select() can return a new SelectListIterator<TSource, TResult> or a SelectIListIterator<TSource, TResult> or a new SelectIPartitionIterator<TSource, TResult> or various other classes, depending on the type of the IEnumerable<> input.

Upvotes: 2

Related Questions