【问题标题】:Simplifying LINQ query in C#在 C# 中简化 LINQ 查询
【发布时间】:2020-02-04 09:23:27
【问题描述】:

表1

Table1ID   Name  Graduation Version Hobbies  
1            A       Degree    1        B
2            A       Degree    2        C
3            A       Degree    3        D

表2

Table2ID   Table1ID Name  Graduation  Version Address Surname    Date
1              1       A      Degree       1      A     A           08-10-2019
2              2       A      Degree       2      A     A           08-10-2019
3              3       A       Degree      3       A    A

//我要检查Table1中是否存在大于最高版本的版本。其中Table2中的Date列不为null 假设 Name 和 Degree 的组合,Table2 中的最高版本是 2,因为 Table2 的 Date 为空,我想检查 Table1 中是否存在大于 2 的记录,如果是,则将其添加到新列表中

这就是我正在做的事情。

List<Table2> groupByTable2 = //Operations on Table2 and get highest Version record from db
List<Table1> check = new List<Table1>();
List<Table1> check2 = await _table1.GetAll().ToListAsync();
Foreach(var a in groupByTable2)
{
   List<Table1> check4 = check2.Where(x => x.Name == a.Name && x.Graduation == a.Graduation).ToList();
  If(check4.Any(x=>x.Version > a.Version))
  { 
     check.Add(check2.Where(x=>x.Table1ID == a.Table1ID).First());
  }
}

现在我的支票包含一条 ID 为 3 的记录。但是有没有更简单的方法可以以更简单的方式实现这一点并具有可读性和性能?

【问题讨论】:

  • "GetAll" 听起来像是整个表从数据库读入内存。您可以跳过所有 .ToList() 并只在数据库中执行 .Any 。要执行的命令更多,但数据可能要少得多

标签: c# asp.net .net linq


【解决方案1】:

我希望我理解您想要达到的目标。您可以尝试以下方法。

var result = table2.Where(x=>x.Date!=null)
                   .GroupBy(x=> new {x.Name, x.Graduation})
                   .SelectMany(x=> x.OrderByDescending(c=>c.Version).Take(1))
                   .Join(table1,t2=>t2.Table1ID,t1=>t1.Table1ID,(t2,t1)=>t1)
                   .ToList();
result.AddRange(table1.Where(x=> result.Any(c=>c.Name.Equals(x.Name) 
                                            && c.Graduation.Equals(x.Graduation) 
                                            && c.Version < x.Version)));    

这个想法是首先使用GroupBy 和 Join 来获取Table1 中具有最高Version 编号的项目列表,该列表在Table2 中具有有效日期。然后,使用List.AddRangeTable1 添加剩余的更高版本。

【讨论】:

    猜你喜欢
    • 2018-02-16
    • 1970-01-01
    • 2019-06-15
    • 2022-12-13
    • 1970-01-01
    • 1970-01-01
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多