【问题标题】:LINQ Sort Distinct with Where clauseLINQ Sort Distinct with Where 子句
【发布时间】:2021-08-04 11:02:08
【问题描述】:

我正在寻求有关 LINQ 语句的帮助;首先,我有一个包含两列的列表,它们是用户帐户和他们的访问级别。

AccountID |  Access
-------------------
1374      |   4
1832      |   1
1383      |   1
1182      |   2

以上列表是从会话缓存中获取的。

List<myUsers> users = new List<myUsers>();
users = myUsers.GetFromUserSession();

我现在想做的是创建一个新列表,其中仅包含访问权限大于或等于 3 的 AccountID 列表。这是我一直在玩的地方,但我不知道如何正确包含 Where 语句。例如,智能感知不允许我介绍 x.Access 之类的东西。

List<int> adminList = myUsers.Select(x => x.AccountID).Where(x => x >= 3).Distinct().ToList()

我现在只是在修补它,直到某些东西起作用,但我想我会问社区,因为我确信这对某些人来说很容易完成。

【问题讨论】:

    标签: c# linq lambda


    【解决方案1】:

    您的查询结构错误

    var admins = myUsers.Where(x => x.Access >= 3)
              .Select(x => x.AccountID)
              .Distinct()
              .ToList()
    

    【讨论】:

      【解决方案2】:

      通过在where 之前执行select,您只会得到AccountID,因此您将where 应用于AccountID

      应该是

      List<int> adminList =myUsers.Where(x => x.Access >= 3).Select(x => x.AccountID).Distinct().ToList()
      

      【讨论】:

        【解决方案3】:

        您必须先使用Where,然后从myUsersAccountID)中选择您想要的:

        List<int> adminList = myUsers
            .Where(x => x.Access >= 3)
            .Select(x => x.AccountID) // here x is still the myUsers instance
            .Distinct()
            .ToList();
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-08-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-08-02
          相关资源
          最近更新 更多