c# - Linq.Except的更多 "SQL-syntax"

标签 c# linq syntax

Linq 中的大多数表达式都可以用两种语法编写。
基本上,方法语法类似 SQL 的语法

例如:

方法语法:
var results = MySet.Where(n => n.Status == State.ACTIVE);

类似 SQL 的语法:
var results = from n in MySet 其中 n.Status == State.ACTIVE 选择 n;

我想在类似 SQL 的语法中使用 .Except,但只能在网上找到它在方法语法中使用的示例。

例子:

int[] numbers = Enumerable.Range(1,20).ToArray();
int[] primes = new[] { 2, 3, 5, 7, 11, 13, 17 };

//var composites = from n in numbers select n except primes; // This does not work.
var composites = numbers.Except(primes);                     // This works
return composites;

问题
我所说的方法语法和类似 SQL 的语法有正式名称吗?
有没有办法在 except 操作上执行类似 SQL 的语法?

最佳答案

C# 中唯一支持 LINQ 语法的方法是:

Where      // where
Select     // select / let
SelectMany // from
Join       // join
GroupBy    // group by
GroupJoin  // join into

甚至不是所有这些重载。对于其他任何事情,您都必须自己调用方法。

使用 LINQ 语法执行查询的唯一方法是将 Except 换成 GroupJoin:

int[] numbers = Enumerable.Range(1, 20).ToArray();
int[] primes = new[] { 2, 3, 5, 7, 11, 13, 17 };

var composites = from n in numbers
                 join p in primes on n equals p into grp
                 where !grp.Any()
                 select n;

不过,这可能不值得——它的效率会有所降低,并且对于那些没有扎实掌握 LINQ 的人来说可能不会立即理解。

F# 支持更多的 query expressions .希望他们能将其中的一些带到 C# 中。

关于c# - Linq.Except的更多 "SQL-syntax",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20379810/

相关文章:

c# - AddDbContext 在 ASP.NET Core Razor 页面的配置服务中不起作用

c# - WPF:加载 XAML 文件,其中包含 x:Code 元素

vb.net - 隐式转换 : Nullable(Of T) => T | VB. NET LINQ 查询语法与方法语法

c# - 使用 linq C# 从数据表中查找 "false"的编号

LINQ 加入 Where 子句

python - numpy.loadtxt 跳过多行

python - 如何对类中的多个方法设置偏差?

c# - 阻止 List.Add() 方法

c# - 在 Asp.Net Core 解决方案发布时转换 app.config 文件?

java - 什么是java android开发的最佳IDE