locked
How to convert the below to Async Call RRS feed

  • Question

  • User-1188570427 posted

    How would I convert this to an ASYNC call?

    public class Foo
    {
        public int Id { get; set; }
        public int? ParentId { get; set; }  
        // other props
    }

    You can get children of one item using:

    List<Foo> GetChildren(List<Foo> foos, int id)
    {
        return foos
            .Where(x => x.ParentId == id)
            .Union(foos.Where(x => x.ParentId == id)
                .SelectMany(y => GetChildren(foos, y.Id))
            ).ToList();
    }

    For ex.

    List<Foo> foos = new List<Foo>();
    
    foos.Add(new Foo { Id = 1 });
    foos.Add(new Foo { Id = 2, ParentId = 1 });
    foos.Add(new Foo { Id = 3, ParentId = 2 });
    foos.Add(new Foo { Id = 4 });
    
    GetChild(foos, 1).Dump(); // will give you 2 and 3 (ids)
    Tuesday, April 3, 2018 8:30 PM

Answers

  • User1400794712 posted

    Hi tvb2727,

    If you want to call GetChildren() asynchronously, you can use async-await for it.

    async Task<List<Foo>> GetChildren(List<Foo> foos, int id)
    {     
        var re = await foos.AsQueryable() 
            .Where(x => x.ParentId == id)
            .Union(foos.Where(x => x.ParentId == id)
                .SelectMany(y => GetChildren(foos, y.Id).Result)
            ).ToListAsync() ;
        return re;
    }

    If you want to call this method in MVC controller, we should also add async for the action:

    public async Task<ActionResult> LinqTask()
    {
        List<Foo> foos = new List<Foo>();
    
        foos.Add(new Foo { Id = 1 });
        foos.Add(new Foo { Id = 2, ParentId = 1 });
        foos.Add(new Foo { Id = 3, ParentId = 2 });
        foos.Add(new Foo { Id = 4 });
    
        var list = await GetChildren(foos, 1);
        return View();
    }

    Best Regards,

    Daisy

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, April 4, 2018 3:20 AM