加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – Linq和Async Lambdas

发布时间:2020-12-15 19:27:03 所属栏目:百科 来源:网络整理
导读:以下代码…… 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) { i
以下代码……

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,5 };

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

它对我来说确实有点麻烦,但它实现了你的目标.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读