Cannot implicitly convert type 'System.Collections.Generic.List<>' to 'System.Collections.Generic.IEnumerable'

asp.net-mvc c# entity-framework entity-framework-core

Question

I want to return list of string in function :

private async Task<IEnumerable<string>> GetAccessLevels(Guid roleId)
{
    return await AccessLevels.Where(x => x.RoleId == roleId).Select(x=>new {x.Access }).ToListAsync();
}

But it show me this error :

Cannot implicitly convert type 'System.Collections.Generic.List<<anonymous type: string Access>>' to 'System.Collections.Generic.IEnumerable<string>'. An explicit conversion exists (are you missing a cast?)

This is my model :

public Guid RoleId { get; set; }
public string Access { get ; set; }

How can I solve this problem?

1
0
4/17/2020 3:20:24 PM

Accepted Answer

Just change this:

Select(x => new { x.Access })

To This:

Select(x => x.Access)

The reason is, new makes your query to return an IEnumerable of Anonymous types, while you need an IEnumerable of Strings.

1
4/17/2020 5:17:24 PM

Popular Answer

I think you just need to do as follow:

private async Task<IEnumerable<string>> GetAccessLevels(Guid roleId)
{
    return await AccessLevels.Where(x => x.RoleId == roleId).Select(x=> x.Access).ToListAsync();
}

No need to create an anonymous object in the Select.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow