tags:

views:

46

answers:

4

given the following code:

string[]  colors = {"red","green","blue","red","green","blue"};
var distinctColors = (from c in colors select c).Distinct();
distinctColors.Dump();

Is it possible to fold the call .Distinct() into the embedded query syntax?

something like int T-SQL

select distinct color from TableofColors
+1  A: 

Query comprehension syntax does not support the Distinct method.

In your case, you could simply write colors.Distinct(); you're not doing anything with the query expression.

SLaks
A: 

There's no distinct embedded query syntax in C# as far as I'm aware. This is as close as it gets:

var distinctColors = (from color in colors
                      select color).Distinct()
Sander Rijken
A: 

You can try this

var dis = from c in colors
   group c by c;

foreach (var cVal in dis)
   {
      string s = cVal.Key;
   }
astander
This will return an `IEnmerable<IGrouping<String>>`, not an `IEnumerable<String>`.
SLaks
You should write `from c in colors group c by c into c select c.Key`. Also, it'll probably be a bit slower than `Distinct`.
SLaks
SLaks. Do you have any stats proving group by slower thatn distinct?
astander
No; that's why I said _probably_.
SLaks
I just tried it in LINQPad using the array in the question; `Distinct` was roughly twice as fast.
SLaks
+4  A: 

C#'s query expression syntax doesn't include "distinct". VB's does, however - for example, from the MSDN docs for VB's Distinct clause:

// VB
Dim customerOrders = From cust In customers, ord In orders _
                     Where cust.CustomerID = ord.CustomerID _
                     Select cust.CompanyName, ord.OrderDate _
                     Distinct

The C# equivalent would have to explicitly call Distinct() in dot notation.

However, your example can still be simplified:

string[]  colors = {"red","green","blue","red","green","blue"};
var distinctColors = colors.Distinct();
distinctColors.Dump();

Don't think you have to use query expressions to use LINQ :)

Jon Skeet