开发者

Can Distinct be expressed using so-called embedded query rather than a method call

开发者 https://www.devze.com 2022-12-14 12:21 出处:网络
given the following code: string[]colors = {\"red\",\"green\",\"blue\",\"red\",\"green\",\"blue\"}; var distinctColors = (f开发者_如何转开发rom c in colors select c).Distinct();

given the following code:

string[]  colors = {"red","green","blue","red","green","blue"};
var distinctColors = (f开发者_如何转开发rom 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


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 :)


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()


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.


You can try this

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

foreach (var cVal in dis)
   {
      string s = cVal.Key;
   }
0

精彩评论

暂无评论...
验证码 换一张
取 消