Entity Framework Core Select Property with multiple conditions

asp.net-core entity-framework-core linq

Question

I have this query in 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.

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
1
1
8/28/2019 11:48:30 AM

Accepted Answer

Have a separate method to do the logic for simplicity. Then use that in the Select statement.

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.

1
8/28/2019 11:52:35 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow