【问题标题】:Using LINQ in .Net 3.1 to get all items from a database table that matches a list of ID's在 .Net 3.1 中使用 LINQ 从与 ID 列表匹配的数据库表中获取所有项目
【发布时间】:2020-12-01 13:22:00
【问题描述】:

我有一个 SQL 数据库和一个 .Net core 3.1 项目,其中包含 3 个名为 members、memberships 和 clubs 的表。 每个成员都是独一无二的,具有唯一的 MemberId,并且可以是多个俱乐部的一部分。 对于每个俱乐部,会员都是您的一部分,会员表中有一行包含 MemberId、ClubId 和 MembershipID。

会员:

|ID|会员ID|俱乐部ID| ******************** |1 |1 |1 | |1 |1 |2 | |2 |2 |2 | |3 |3 |3 | |3 |3 |2 | |3 |3 |1 |

俱乐部:

|Id|姓名 |主题| ************************ |1 |国际象棋俱乐部 |国际象棋 | |2 |狐步舞 |舞蹈 | |3 |油漆俱乐部 |艺术 |

成员:

|Id|名字 |电话 | ************************ |1 |鲍勃 |xxx | |2 |曼迪 |yyy | |3 |乔 |zzz |

我有一个包含所有需要匹配的 clubId 的列表。 现在使用 Linq,我想获取属于多个俱乐部的所有成员。因此,例如,我想获取属于国际象棋俱乐部(ID:1)和油漆俱乐部(ID:3)的所有成员,因此在这种情况下只有 Joe 的列表 [1, 3]。

这是一个相当简化的伪代码版本,但我希望它有助于演示我想要做什么。

members.Where(membership => members.clubId == 1 AND members.clubId == 3)

这显然行不通,因为没有单行可以满足这一点,而且我希望它与 clubId 的列表一起动态。

var memberClubData = [1,3] members.Where(membership => memberClubData.All(x => x == members.clubId))

我知道如何使用带有子查询和计数的 SQL 来执行此操作,但在 C# 中使用 LINQ 执行此操作时我完全卡住了。

【问题讨论】:

  • 通常你会创建一个你想要的项目列表,比如 List findClubId = new List() {1,3};然后您可以使用 findClubId.Contains(x) 作为查询的一部分。
  • @jdweng 当我这样做时,我得到了属于 clubId 1 或 3 的每个人,而我实际上只想要同时属于两个俱乐部的人,也就是 Joe。使用包含我得到 Joe 和 Bob 而不是只有 Joe。

标签: c# linq .net-core-3.1


【解决方案1】:

var query= from Member in Members where 会员.Clubs.any(club=>club.Id==1 && club.Id==3) 选择会员

【讨论】:

    【解决方案2】:

    尝试以下:

               DataTable memberships = new DataTable();
                memberships.Columns.Add("Id", typeof(int));
                memberships.Columns.Add("MemberId", typeof(int));
                memberships.Columns.Add("ClubId", typeof(int));
    
                memberships.Rows.Add(new object[] { 1,1,1});
                memberships.Rows.Add(new object[] { 1,1,2});
                memberships.Rows.Add(new object[] { 2,2,2});
                memberships.Rows.Add(new object[] { 3,3,3});
                memberships.Rows.Add(new object[] { 3,3,2});
                memberships.Rows.Add(new object[] { 3,3,1});
    
                List<int> findClubId = new List<int>() {1,3};
    
                int[] memberClubData = memberships.AsEnumerable()
                    .Select(x => new { id = x.Field<int>("Id"), clubId = x.Field<int>("ClubId") })
                        .GroupBy(x => x.id)
                        .Where(x => findClubId.All(y => x.Select(z => z.clubId).Contains(y)))
                        .Select(x => x.First().id)
                        .ToArray();
    

    【讨论】:

      猜你喜欢
      • 2019-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-14
      • 1970-01-01
      • 2011-03-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多