Home > Software engineering >  C# list sort with OR condition
C# list sort with OR condition

Time:10-30

I'm trying to sort a list that comes from my database. If all fields in my OrderFunds column are null, I want to sort by another column. Can anyone tell me how to do this?

This is my code:

List<Fund> funds = await fundSupervisor.List().Where(fund => fund.IsActive)
                                              .OrderBy(fund => fund.OrderFunds)

Or, my OrderBy clause can allow null values. That would help me too.

CodePudding user response:

If you need to sort totally different if, and only if all columns are null, you need to check that in advance.

List<Fund> funds = await fundSupervisor.List().Where(fund => fund.IsActive)
if(funds .Any(item => item.OrderFunds != null))
    funds = funds.OrderBy(fund => fund.OrderFunds);
else
    funds = funds.OrderBy(fund => fund.SomethingElse);

Otherwise, if you want to sort by another value if OrderFunds is null, then you can simply use a condition inside the OrderBy.

var orderedFunds = funds.OrderBy(fund => fund.OrderFunds ?? SomeOtherValue);

If you want to sort by another value as secondary sorting, use a ThenBy. That sorts all values by the ThenBy-value if there are multiple same values in the OrderBy-operation.

var orderedThenByFunds = funds.OrderBy(fund => fund.OrderFunds).ThenBy(fund => fund.SomeOtherValue);

Consider that these lines are different: Say you have 3 items (assumed OrderFunds is int?:

Fund1 { OrderFunds = 1, SomeOtherValue = 8 }
Fund2 { OrderFunds = 3, SomeOtherValue = 6 }
Fund3 { OrderFunds = null, SomeOtherValue = 4 }
Fund4 { OrderFunds = null, SomeOtherValue = 2 }

Then orderedFunds would return Fund1(1), Fund4(2[SomeOtherValue]), Fund2(3), Fund3(4[SomeOtherValue]) and orderedThenByFunds would return Fund1(1,8), Fund2(3,8), Fund4(null,2), Fund3(null,2). The values in braces are the values ordered by.

CodePudding user response:

This is the solution

List<Fund> funds = fundSupervisor
.Where(w => w.IsActive)
.OrderBy(w => w.OrderFunds)
.ThenBy(w => w.OtherField).ToList();

ThenBy() allows you specify other fields to sort your list.

  • Related