首页 > 解决方案 > 使用 Linq 查询并计算 Where 子句中的匹配项并进行投影

问题描述

需要查询许多列以查找可能的匹配项,然后查看有多少匹配项并将其添加到 Select 投影中的列中。我可以有四列中的两列,但有多少?然后想按多少匹配对结果进行排序。我需要先将它们分组吗?做一个单独的聚合?有点难为要走哪条路,因为真正的路要在生产中进行更多的测试。在 where 子句中可能匹配多达 8 个测试。

    var results = _RList
       .Where(d => d.RMI15Min == RMI.ConfirmedBottom || d.RMI15Min == RMI.InPlaceBottomConfirmed
        || d.RMI30Min == RMI.ConfirmedBottom || d.RMI30Min == RMI.InPlaceBottomConfirmed)
       .OrderBy(d => d.Instrument)
       .Select(d => new
       {
           d.Instrument,
           d.Description,
           d.RMI15Min,
           d.RMI30Min,
           NewColumn with the total of the matches in the .Where clause above. 
       }).ToList();

标签: c#linq

解决方案


假设_RList不绑定到数据库表

var confirmedList = new List<int> { RMI.ConfirmedBottom, RMI.InPlaceBottomConfirmed };
var results = _RList
       .OrderBy(d => d.Instrument)
       .Select(d => new
       {
           d.Instrument,
           d.Description,
           d.RMI15Min,
           d.RMI30Min,
           Count = (new List<int> { d.RMI15Min, d.RMI30Min }).Count(c => confirmedList.Contains(c))
       })
       .Where(d => d.Count > 0)
       .ToList();

如果它与数据库表相关联,则取决于您的库是否可以转换上述 LINQ 语句。


推荐阅读