-1
     public class Role
        {
            public int RoleId { get; set; }

            public string RoleName { get; set; }
        }

 public class Program
    {
        static void Main(string[] args)
        {
            List<Role> Roles = new List<Role>();

            Roles.Add(new Role { RoleId = 1, RoleName = "Admin" });
            Roles.Add(new Role { RoleId = 2, RoleName = "User" });
            Roles.Add(new Role { RoleId = 3, RoleName = "SuperUser" });
            Roles.Add(new Role { RoleId = 4, RoleName = "NormalUser" });

            int[] roleid = { 1, 4, 5 };

           }
    }

In my session I have multiple roleId so based on my login so i want to retrieve role name from Roles list using Linq without foreach loop

bharat
  • 79
  • 1
  • 11
  • you want to get it by index? like ``List[0], List[3],List[4]`` – Mohammed Sajid Apr 14 '20 at 20:46
  • Thanks for reply but search query is dynamic is always changes – bharat Apr 14 '20 at 20:55
  • 1
    yeah, but if you have 1,2,3, i don't know why you need to search the same things in list that contains just integer. maybe your question is not clear. the input and the output are the same. – Mohammed Sajid Apr 14 '20 at 20:59
  • Real use case is I have list of users and I want to retrieve specific user based on its login search users can be changes – bharat Apr 14 '20 at 21:08

2 Answers2

2

You can use Linq Where and Contains methods:

int[] elementsToSearch = [1, 4, 5];
List<int> filteredList = list.Where(x => elementsToSearch.Contains(x)).ToList();
Renan Araújo
  • 3,533
  • 11
  • 39
  • 49
0

This works

    static void Main(string[] args)
    {
        Console.WriteLine("Hello World!");
        List<int> list = new List<int>();

        list.Add(1);
        list.Add(2);
        list.Add(3);
        list.Add(4);
        list.Add(5);
        list.Add(6);
        list.Add(7);
        list.Add(8);

        var lstSel = from l in list where l == 4|| l==1 || l == 5 select l; 
    }
Mark Wardell
  • 493
  • 7
  • 25