给出以下代码:
string[] colors = {"red","green","blue","red","green","blue"};
var distinctColors = (from c in colors select c).Distinct();
distinctColors.Dump();
是否可以将调用.Distinct()
折叠为嵌入式查询语法?
类似于int T-SQL
select distinct color from TableofColors
答案 0 :(得分:8)
C#的查询表达式语法不包含“distinct”。然而,VB的确如此 - 例如,来自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
C#等效项必须以点表示法显式调用Distinct()
。
但是,您的示例仍然可以简化:
string[] colors = {"red","green","blue","red","green","blue"};
var distinctColors = colors.Distinct();
distinctColors.Dump();
不要认为 使用查询表达式来使用LINQ:)
答案 1 :(得分:2)
据我所知,C#中没有明显的嵌入式查询语法。这很接近:
var distinctColors = (from color in colors
select color).Distinct()
答案 2 :(得分:1)
查询理解语法不支持Distinct
方法。
在你的情况下,你可以简单地写colors.Distinct()
;你没有对查询表达式做任何事情。
答案 3 :(得分:0)
你可以试试这个
var dis = from c in colors
group c by c;
foreach (var cVal in dis)
{
string s = cVal.Key;
}