Search code examples
c#lambdalinq-to-entities

C# Lambda expression to pull all names by comma separated ids


I have roled ids in a comma separated string. I am trying to pull role names from db based on the role id each separately inside loop.

Is there any option to get all rolenames at once using linq or lambda expression?

For example I have

var roleIds = "1,3,5,9";

Similar to the lambda expression below to pull one role name can I pull all role names for role ids in a single line code with out a loop?

for (var i; i < mycommaseperatedRoleIds.count; i++)
    var roleName = db.Roles.Where(k => k.Id == roleId).Select(p => p.Role);

Solution

  • You can do something like this:

    var roleIds ="1,3,5,9".Split(',').Select(s => int.Parse(s));
    
    var roleNames = db.Roles.Where(k => roleIds.Contains(k.Id)).Select(p => p.Role);