Reputation: 1346
How to order a list with condition
As an example:
I have a list of INTs
{1,45,63,1,2,100,46,12,2,100}
in code:
int[] ints = {1,45,63,1,2,100,46,12,2,100};
I want to order in two ways ASC and DESC means:
switch (this.SortMode)
{
case ReportSortMode.DESC:
Rank = Rank.OrderByDescending();
break;
case ReportSortMode.ASC:
Rank = Rank.OrderBy();
break;
}
but i need to get values in condition:
ASC: {1,1,2,2,12,45,46,63,100,100}
DESC: {63,46,45,12,2,2,1,1,100,100}
means:
Where(x =>x < 100)
possible using Except
some like :
var fakeval = rank.where(x => x<100)
switch (this.SortMode)
{
case ReportSortMode.DESC:
Rank = Rank.OrderByDescending().Except(fakeval);
break;
case ReportSortMode.ASC:
Rank = Rank.OrderBy();
break;
}
//to be full))
public enum ReportSortMode
{
DESC = 1,
ASC = 2,
}
but it's no work
Upvotes: 2
Views: 2190
Reputation: 8591
For ASC order you need to change nothing:
var intsasc = ints.OrderBy(x=>x);
For DESC order below code should be OK:
var intsdesc = ints.OrderByDescending(x=>x<100 ? 1 : 0).ThenByDescending(x=>x);
Result:
63
46
45
12
2
2
1
1
100
100
Upvotes: 5
Reputation: 22945
ASC:
ints
.OrderBy(x => x < 100)
.ThenBy(x => x)
DESC:
ints
.OrderBy(x => x < 100)
.ThenByDescending(x => x)
Note: not entirely sure if true comes before false or the other way around. You might need to change OrderBy to OrderByDescending.
Upvotes: 2