gpt4 book ai didi

c# - Linq 和异步 Lambda

转载 作者:太空狗 更新时间:2023-10-29 22:13:34 27 4
gpt4 key购买 nike

下面的代码...

using System;
using System.Linq;
using System.Threading.Tasks;

namespace ConsoleAsync
{
class Program
{
static void Main(string[] args)
{
MainAsync(args).Wait();
Console.ReadLine();
}

static async Task MainAsync(string[] args)
{
int[] test = new[] { 1, 2, 3, 4, 5 };

if (test.Any(async i => await TestIt(i)))
Console.WriteLine("Contains numbers > 3");
else
Console.WriteLine("Contains numbers <= 3");
}

public static async Task<bool> TestIt(int i)
{
return await Task.FromResult(i > 3);
}
}
}

给你以下错误:-

CS4010: Cannot convert async lambda expression to delegate type 'Func<int, bool>'. An async lambda expression may return void, Task or Task<T>, none of which are convertible to 'Func<int, bool>'.

在线

if (test.Any(async i => await Test.TestIt(i)))

您如何使用 Async Lambdas 和 linq?

最佳答案

您不能开箱即用 LINQ。但是您可以编写一个小的扩展方法来完成这项工作:

public static class AsyncExtensions
{
public static async Task<bool> AnyAsync<T>(
this IEnumerable<T> source, Func<T, Task<bool>> func)
{
foreach (var element in source)
{
if (await func(element))
return true;
}
return false;
}
}

然后像这样消费它:

static async Task MainAsync(string[] args)
{
int[] test = new[] { 1, 2, 3, 4, 5 };

if (await test.AnyAsync(async i => await TestIt(i))
Console.WriteLine("Contains numbers > 3");
else
Console.WriteLine("Contains numbers <= 3");
}

我确实觉得有点麻烦,但它达到了你的目的。

关于c# - Linq 和异步 Lambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36445257/

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