gpt4 book ai didi

c# - IQueryable.Where() 到底发生了什么?

转载 作者:行者123 更新时间:2023-11-30 21:20:00 25 4
gpt4 key购买 nike

这是根据是否有一些匹配的 ID 返回一个 bool 值。

from t in getAll
select new Result
{
...
bool DetailsAvailable =
(db.SaveTrackings.Where(s => s.BundleID == t.bundleID
&& s.UserID == t.userID)
.Count() > 0) ? true : false;
}

这是我认为理解的:.Where()正在返回具有匹配 ID 的所有条目,然后是 .Count()只是看看有多少人。我只觉得我对我们需要的东西了解了一半s为。

我知道这段代码会带来什么,因为它一直在使用中,我只是不明白它是如何工作的,而且 MSDN 的一些文档使用了一些让我感到困惑的术语。

All lambda expressions use the lambda operator =>, which is read as "goes to". The left side of the lambda operator specifies the input parameters (if any) and the right side holds the expression or statement block. The lambda expression x => x * x is read "x goes to x times x."

那么我应该如何理解基于此的代码的含义,.Where(s “去”s.BundleID == t.BundleID ...)那么这里发生了什么? “去”是什么意思?是否比较s中的每个ID给每个人一个可用的 t ?我如何理解为什么它被称为“goes to”以及究竟发生了什么?

然后它变得更加困惑......

The => operator has the same precedence as assignment (=) and is right-associative.

Lambdas are used in method-based LINQ queries as arguments to standard query operator methods such as Where.

When you use method-based syntax to call the Where method in the Enumerable class (as you do in LINQ to Objects and LINQ to XML) the parameter is a delegate type System.Func. A lambda expression is the most convenient way to create that delegate.

什么是委托(delegate)类型 System.Func<T, TResult>以及它是如何用这个“转到”运算符创建的?

我不能只使用代码,因为我知道它在工作,我需要了解如何/为什么。

最佳答案

也许看到手工实现这个功能会有所帮助:

using System;
using System.Collections.Generic;

namespace CSharpSandbox
{
class Program
{
static IEnumerable<T> Where<T>(IEnumerable<T> input, Func<T, bool> predicate)
{
foreach (T item in input)
{
if (predicate(item))
yield return item;
}
}

static void Main(string[] args)
{
int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
IEnumerable<int> evens = Where(numbers, n => n % 2 == 0);
foreach (int even in evens)
{
Console.WriteLine(even);
}
}
}
}

构造 name => someEvaluation创建一个由以下部分组成的匿名函数:

  • name只是一个参数的名称,它的类型是从它的用法中推断出来的。您需要一个名称,以便您可以引用函数中传递的参数。
  • =>是匿名函数主体的开始,主体的范围是单个表达式。
  • someEvaluation是由单个表达式组成的匿名函数的主体。

在我们的例子中,Func<T, bool>定义一个函数,它接受一个类型为 T 的参数并返回 bool 类型的输出. (如果我们使用了 Func<T, U, bool> ,我们将采用 TU 类型的两个输入并返回一个 boolFunc 定义中的最后一个类型参数是返回值。)

您可以调用 Func 的一个实例就像您调用任何其他函数一样。如果 func 接受参数,您按预期传递它们,您的参数将绑定(bind)到您定义的变量名。当您调用该函数时,控制流将跳转到您的函数内部并评估其结果。

原则上,您不需要创建 Func匿名。您可以传入具有兼容类型签名的任何函数,例如:

    static bool IsEven(int n)
{
return n % 2 == 0;
}

static void Main(string[] args)
{
int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
IEnumerable<int> evens = Where(numbers, IsEven);
foreach (int even in evens)
{
Console.WriteLine(even);
}
}

这个程序产生相同的输出。事实上,在幕后,语法 name => expression是语法糖;当它被编译时,C# 将生成一个带有隐藏名称的私有(private)函数,并将其转换为上述格式。

关于c# - IQueryable.Where() 到底发生了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3513969/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com