Matthew Flynn
Matthew Flynn

Reputation: 3941

Error in Linq Query when using anonymous return on List

I have the following linq query, where I want to return the total number of each StatusType as a list.

    public async Task<ServiceResponse<IList<(StatusType StatusType, int Count)>>> GetSummaryByStatusTypeAsync()
    {
        Func<Task<IList<(StatusType StatusType, int Count)>>> func = async () =>
        {
            using (var context = _contextFactory())
            {
                var items = (await context.ToListAsync<Job>(x => x
                                .Include(y => y.Status)))
                            .GroupBy(x => x.Status.StatusType)
                            .Select(x => new
                            {
                                StatusType = x.Key,
                                Count = x.Count()
                            }).ToList();

                return items;
            }
        };

        return await this.ExecuteAsync(func);
    }

However, I get the errors;

CS0266 Cannot implicitly convert type 'System.Collections.Generic.List<<anonymous type: Core.StatusType StatusType, int Count>>' to 'System.Collections.Generic.IList<(Core.StatusType StatusType, int Count)>'. An explicit conversion exists (are you missing a cast?)

CS4010 Cannot convert async lambda expression to delegate type 'Task<IList<(StatusType StatusType, int Count)>>'. An async lambda expression may return void, Task or Task, none of which are convertible to 'Task<IList<(StatusType StatusType, int Count)>>'.

Upvotes: 0

Views: 237

Answers (1)

Afshin Mobayen Khiabani
Afshin Mobayen Khiabani

Reputation: 1289

Your function return type is not anonymous. It's tuple. You can do this:

var items = (await context.ToListAsync<Job>(x => x
                                .Include(y => y.Status)))
                            .GroupBy(x => x.Status.StatusType)
                            .AsEnumerable()
                            .Select(x => (x.Key, x.Count()))
                            .ToList();

                return items;

Upvotes: 2

Related Questions