c# - 使用 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();
解决方案
假设_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 语句。
推荐阅读
- regex - 在分隔符之间使用 CLRF 更正 .csv 文件
- file - 使用 Python 3.6 解析、编辑和保存 dhcpd.conf 文件
- java - ReactJS 和 Java:对预检请求的响应未通过访问控制检查
- angular - 从 API 值更改字体颜色时出现角度错误
- docker - 由于端口限制,无法构建 dockerfile
- linux - noob - 语法错误:重定向意外
- neo4j - 是否可以在关系 NEO4J 上创建约束?
- javascript - 删除以前添加的类不起作用
- xamarin - Xamarin.Forms Shell - 不能使用 ShellContent,除非在
? - c# - 使用 ASP.NET MVC 应用程序与 Windows 服务的 Entity Framework 的行为不一致