如何将 Linq 查询扩展方法与其文档中的签名相关联?

问题描述 投票:0回答:2

MSDN获取此代码:

以下代码示例演示了如何使用 Where(IEnumerable, Func) 进行过滤 一个序列。

List<string> fruits =
    new List<string> { "apple", "passionfruit", "banana", "mango", 
                    "orange", "blueberry", "grape", "strawberry" };

IEnumerable<string> query = fruits.Where(fruit => fruit.Length < 6);

foreach (string fruit in query)
{
    Console.WriteLine(fruit);
}
/*
 This code produces the following output:

 apple
 mango
 grape
*/

当我看到签名时,

Where<TSource>(IEnumerable<TSource>, Func<TSource, Boolean>)

(fruit => fruit.length < 6)
的哪一部分是
IEnumerable<TSource>
Func<TSource, Boolean>
包含整个 lambda 还是仅包含
=>
之后的内容?我猜测在幕后Where's
<TSource>
被编译器替换为通用的正确类型,但我不知道如何阅读其余部分。

编辑:如果这是一个委托而不是 lambda,就看看文档中的内容指向什么内容会更容易理解吗?

c# linq extension-methods
2个回答
3
投票

如果您查看方法签名,您会发现它定义为

public static Enumerable
{
    public static IEnumerable<TSource> Where<TSource>(
        this IEnumerable<TSource> source,
        Func<TSource, bool> predicate
    )
}

this
使其成为一种扩展方法。这样做

fruits.Where(fruit => fruit.Length < 6);

与做的事情完全相同

Enumerable.Where(fruits, fruit => fruit.Length < 6);

因此,要回答您的问题,

IEnumerable<T>
位于
.

的左侧

0
投票

如果我内联编写查询,是否存在性能问题?

foreach (string fruit in fruits.Where(fruit => fruit.Length < 6))
{
    Console.WriteLine(fruit);
}
© www.soinside.com 2019 - 2024. All rights reserved.