[英]Query with Linq and count matches in the Where clause and project it
需要查询许多列以查找可能的匹配项,然后查看有多少匹配项并将其添加到 Select 投影中的列中。 我可以有四列中的两列,但有多少? 然后想按多少匹配对结果进行排序。 我需要先将它们分组吗? 做一个单独的聚合? 有点难倒 go 的方式,因为真正的生产现场会有更多的测试。 在 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 语句。
我会考虑使用三元运算符将 1/0 添加到总数中;
Count = (d.RMI15Min == RMI.ConfirmedBottom ? 1 : 0)
+ (d.RMI15Min == RMI.InPlaceBottomConfirmed ? 1 : 0)
+ (d.RMI30Min == RMI.ConfirmedBottom ? 1 : 0)
+ (d.RMI30Min == RMI.InPlaceBottomConfirmed ? 1 : 0)
然后在计算计数后过滤列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.