I have a list of arrays that have a value called status. I want to sort these by placing the arrays with the "Active" status to the front of the list. This is to display the active elements first in a later function. Any good ideas how to sort and place the active "contracts" first?
IEnumerable<Contract> mappedContracts = MapContractsToContracts(contracts);
mappedContracts.OrderBy(x => x.Status == "Active");
return mappedContracts.ToList();
CodePudding user response:
Presuming Status
is a string
and other statuses are not alphabetically before "Active"
.
IEnumerable<Contract> mappedContracts = MapContractsToContracts(contracts);
return mappedContracts
.OrderBy(x => x.Status)
.ToList();
For a more rugged approach, in MapContractsToContracts
you could convert the status string to an Enum
or custom type that had its own implementation of IComparable
. In that way, you could define the precedence and order of statuses and verify that the data from the API met your expectations.
CodePudding user response:
As @Jodrell's answer is correct for your specific scenario, I think
a good idea to make it a bit more general is to use an enum
instead of string
for the status property.
public enum Status
{
Active = 0,
Deactive = 1,
}
Then you should change your model:
public class Contract
{
...
public Status Status {get; set;}
...
}
Then you can use the below query, and be sure that contracts with Active
status will always come first.
IEnumerable<Contract> mappedContracts = MapContractsToContracts(contracts);
return mappedContracts
.OrderBy(x => x.Status)
.ToList();
Good Luck.