[英]Entity Framework Core Select Property with multiple conditions
I have this query in linq我在 linq 中有这个查询
var records = _context.Records.Select(r => new{
r.Quantity,
r.CreatedOn,
r.Name,
Group = // if(condition1) value1 | if(condition2) value2 | etc...
})
As you can see i want to be able to create an anonymous property based on many checks so i can use that property for grouping after.如您所见,我希望能够基于许多检查创建一个匿名属性,以便我可以使用该属性进行分组。
The conditions are date constant date checks starting on CreatedOn date.条件是从 CreatedOn 日期开始的日期常量日期检查。
For example,例如,
the first check would be第一个检查是
if(r.CreatedOn.TimeOfDay > r.CreatedOn.TimeOfDay.Add(TimeSpan.FromHours(1)) return 1 // 1st hour
if(r.CreatedOn.TimeOfDay > r.CreatedOn.TimeOfDay.Add(TimeSpan.FromHours(2)) return 2 // 2st hour
if(r.CreatedOn.TimeOfDay > r.CreatedOn.TimeOfDay.Add(TimeSpan.FromHours(3)) return 3 // 3st hour
... up to 8th hour
Have a separate method to do the logic for simplicity.为简单起见,有一个单独的方法来执行逻辑。 Then use that in the Select statement.
然后在 Select 语句中使用它。
private string GroupingLogic(string val1, strinv val2, ...)
{
if(condition 1) return "group-1"
else if(condition 2) return "group-2"
else if(condition 3) return "group-3"
else return "group-3"
}
var records = _context.Records.Select(r => new{
r.Quantity,
r.CreatedOn,
r.Name,
Group = GroupingLogic(r.CreateOn, r.AnyOtherValue)
})
Now in the next step you can use the Group for grouping.现在在下一步中,您可以使用 Group 进行分组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.