I am trying to sort all the items in a list according to their status. I tried to do it in the following way with the Dictionary but it gives me an error. Could you help me to do it correctly?
The order according to their status should be as follows: Activated, Paused, Expired and Drained.
var table = _plapsaContext.Coupons;
var query = _plapsaContext.Coupons.AsQueryable();
query.Select(e => new CouponDto{
Id = e.Id,
StartingDate = e.StartingDate,
EndingDate = e.EndingDate,
Amount = e.Amount,
TotalCoupons = e.TotalCoupons,
MinimumAmount = e.MinimumAmount,
RestCoupons = e.RestCoupons,
ContractId = e.ContractId,
Status = (e.EndingDate.Date < DateTime.Now.Date && e.Status != CouponStatus.Paused && e.Status != CouponStatus.Drained) ? CouponStatus.Expired : e.Status,
ContractCode = e.ContractId.HasValue ? e.Contract.Code.ToString() : null,
OwnerAssociationCode = e.OwnerAssociactionCode,
BuildingManagerName = e.ContractId.HasValue ? e.Contract.BuildingManagerName : null,
ExcludeFunctionalUnits = e.ExcludeFunctionalUnits
});
Dictionary<CouponStatus, int> orderCoupons = new Dictionary<CouponStatus, int>
{
{ CouponStatus.Activated, 0 },
{ CouponStatus.Paused, 1 },
{ CouponStatus.Expired, 2 },
{ CouponStatus.Drained, 3 },
};
Array.Sort(query.ToArray(), (p, q) => orderCoupons[p.Status].CompareTo(orderCoupons[q.Status]));
Console.WriteLine(query);
return (IQueryable<CouponDto>)query;
I hope you can help me! Thank you very much!
CodePudding user response:
This query should sort in desired way. I don't think that you need sorting dictionary here. The following query will sort data on the server side.
var query = _plapsaContext.Coupons.AsQueryable();
var dtoQuery = query
.Select(e => new CouponDto
{
Id = e.Id,
StartingDate = e.StartingDate,
EndingDate = e.EndingDate,
Amount = e.Amount,
TotalCoupons = e.TotalCoupons,
MinimumAmount = e.MinimumAmount,
RestCoupons = e.RestCoupons,
ContractId = e.ContractId,
Status = (e.EndingDate.Date < DateTime.Now.Date && e.Status != CouponStatus.Paused && e.Status != CouponStatus.Drained) ? CouponStatus.Expired : e.Status,
ContractCode = e.ContractId.HasValue ? e.Contract.Code.ToString() : null,
OwnerAssociationCode = e.OwnerAssociactionCode,
BuildingManagerName = e.ContractId.HasValue ? e.Contract.BuildingManagerName : null,
ExcludeFunctionalUnits = e.ExcludeFunctionalUnits
});
dtoQuery = dtoQuery
.OrderBy(e => e.Status == CouponStatus.Activated ? 0
: e.Status == CouponStatus.Paused ? 1
: e.Status == CouponStatus.Expired ? 2
: e.Status == CouponStatus.Drained : 3
);
return dtoQuery;