Home > Back-end >  .NET - Projection and dynamic return type don't match?
.NET - Projection and dynamic return type don't match?

Time:01-28

So I have this method:

public async Task<List<dynamic>> GetIdsOfPersoane()
    {
        return await GetRecords(true).Select(p => new {p.Id, p.Nume}).ToListAsync();
    }

GetRecords retrieves some data from the database.

Basically, I want to use projection but I don't want to create a new object only for this method. So I've done my research and I should return dynamic. I think this would work with object for sure, but I want to avoid boxing and unboxing.

The problem is that I get an error.

Cannot convert expression type 'System.Collections.Generic.List<{int Id, string Nume}>' to return type 'System.Collections.Generic.List<dynamic>

Why is this happening? Shouldn't dynamic work this way?

Thanks.

CodePudding user response:

Setting concerns around strong-typing the return type aside in the public method. You can get around this via ExpandoObject.

return (await GetRecords(true)).Select(p =>
{
  dynamic result = new ExpandoObject();  // returns dynamic type
  result.Id = p.Id;
  result.Nume = p.Nume;

  return result;
})

CodePudding user response:

What you can do to make this compilable - provide generic type parameter for ToListAsync:

async Task<List<dynamic>> GetIdsOfPersoane()
{
    return await GetRecords(true)
        .Select(p => new {p.Id, p.Nume})
        .ToListAsync<dynamic>();
}

Or

async Task<List<dynamic>> GetIdsOfPersoane()
{
    return await GetRecords(true)
        .Select(p => new {p.Id, p.Nume})
        .ToListAsync<object>();
}

What you better do - create a type to return (with records it can be done very easy):

record PersonIdNume(int Id, string Nume);
async Task<List<PersonIdNume>> GetIdsOfPersoane()
{
    return await GetRecords(true)
       .Select(p => new PersonIdNume(p.Id, p.Nume))
       .ToListAsync();
}
  • Related