【问题标题】:How to retrieve specific records from list without foreach loop [duplicate]如何在没有foreach循环的情况下从列表中检索特定记录[重复]
【发布时间】:2020-04-16 12:12:03
【问题描述】:
     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 };

           }
    }

在我的会话中,我有多个 roleId,所以基于我的登录名,所以我想使用 Linq 从角色列表中检索角色名称,而不使用 foreach 循环

【问题讨论】:

  • 您想通过索引获取它吗?喜欢List[0], List[3],List[4]
  • 感谢您的回复,但搜索查询是动态的,总是在变化
  • 是的,但如果你有 1,2,3,我不知道为什么你需要在只包含整数的列表中搜索相同的东西。也许你的问题不清楚。输入和输出是一样的。
  • 真正的用例是我有用户列表,我想根据其登录名检索特定用户搜索用户可以更改

标签: linq


【解决方案1】:

您可以使用 Linq WhereContains 方法:

int[] elementsToSearch = [1, 4, 5];
List<int> filteredList = list.Where(x => elementsToSearch.Contains(x)).ToList();

【讨论】:

    【解决方案2】:

    这行得通

        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; 
        }
    

    【讨论】:

    • 我想要逻辑类似于 where l in (1,4,9) 所以搜索输入是动态的不是固定的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-25
    • 2011-01-15
    • 2010-12-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多