Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ extension SelectMany in 3.5 vs 4.0?

Tags:

c#

linq

When I saw Darins suggestion here ..

IEnumerable<Process> processes = 
    new[] { "process1", "process2" } 
    .SelectMany(Process.GetProcessesByName);

( process.getprocessesbyname() )

.. I was a bit intrigued and I tried it in VS2008 with .NET 3.5 - and it did not compiling unless I changed it to ..

IEnumerable<Process> res = 
  new string[] { "notepad", "firefox", "outlook" }
    .SelectMany(s => Process.GetProcessesByName(s));

Having read some Darins answers before I suspected that it was me that were the problem, and when I later got my hands on a VS2010 with.NET 4.0 - as expected - the original suggestion worked beautifully.

My question is: What have happened from 3.5 to 4.0 that makes this (new syntax) possible? Is it the extensionmethods that have been extended(hmm) or new rules for lambda syntax or?

like image 768
Moberg Avatar asked Jun 17 '10 17:06

Moberg


People also ask

What is the difference between the Select and SelectMany extension methods?

Select and SelectMany are projection operators. A select operator is used to select value from a collection and SelectMany operator is used to selecting values from a collection of collection i.e. nested collection.

What does SelectMany do in LINQ?

The SelectMany in LINQ is used to project each element of a sequence to an IEnumerable<T> and then flatten the resulting sequences into one sequence. That means the SelectMany operator combines the records from a sequence of results and then converts it into one result.

What best describes the SelectMany () Language Integrated Query LINQ extension method?

What best describes the SelectMany() Language Integrated Query (LINQ) extension method? It projects each element of a sequence to an IEnumerable<T> and flattens the resulting sequences into one sequence.

What is SelectMany?

SelectMany(<selector>) method The SelectMany() method is used to "flatten" a sequence in which each of the elements of the sequence is a separate, subordinate sequence.


1 Answers

It seems that the delegate selection is much more intelligent in the new version of C# (C# 4.0 vs. C# 3.0... not the version of .NET.) This idea was available in VS2008, but it had problems resolving which version of the method to use when there were multiple overloads. The method is selected at compilation, so I have to believe that this has more to do with the updated compiler than with the version of .NET. You will probably find that you can use the new overload ability with solutions compiled for .NET 2.0 in VS2010.

For example, this works in VS2008

var ret = new[] { "Hello", "World", "!!!" }.Aggregate(Path.Combine);
// this is the value of ret => Hello\World\!!!
like image 184
Matthew Whited Avatar answered Sep 22 '22 10:09

Matthew Whited