Lets say I have the following data:
EntryID | ColValueText
1113 20
1113 19
1024 20
1113 20
1024 21
1113 23
So In C# using LINQ or any method I want to filter the data like this
EntryID | ColValueText
1113 23
1024 21
That is: group by both columns but get only the last value of colvaluetext against each entryid. I am attaching my code but I am unable to get the last colvaluetext against entryid.
var groupSalesPersonData = (from r in sp
group r by new { r.EntryID, r.ColValueText }
into results
select new GroupByCommonDto
{
ParentGroupById = results.Select(a => a.EntryID).LastOrDefault(),
FieldValue = results.Select(a => a.FieldValue).LastOrDefault(),
Order = results.Sum(x => x.Order),
VehicleProfit = results.Sum(x => x.VehicleProfit),
ColValueText = results.Select(a => a.ColValueText).LastOrDefault()
})
.ToList();
CodePudding user response:
I wouldn't use Linq to solve this problem. You could potentially do it with Aggregate as this is an aggregation problem. I would use a simple foreach and a dictionary
CodePudding user response:
var groupSalesPersonData = (from r in sp
group r by new { r.EntryID}
into results
select new GroupByCommonDto
{
ParentGroupById = results.Select(a => a.EntryID).LastOrDefault(),
ColValueText = results.Select(a => a.ColValueText).LastOrDefault() //Assuming this is a text value and you always want last in the collection.
})
.ToList();
ColValueText if this are numbers using the correct type with correct sort order give you always the right value