1

I have a DataSet that contains a column, call it Type which contains ints. I'm using LINQ to manipulate the DataSet and I want to sort by Type. The Type column only contains 3 values right now (1, 2, 3). I would like to sort so that Type 2 are first in the list and then 1 and 3.

Is there an easy solution for this or am I going to have to customize the OrderBy?

Pete
  • 10,651
  • 9
  • 52
  • 74
  • possible duplicate of [Linq OrderBy against specific values](http://stackoverflow.com/questions/728319/linq-orderby-against-specific-values) – James Sep 26 '12 at 15:07

3 Answers3

7

Few solutions :

table.AsEnumerable()
.OrderBy(r => r.Field<int>("Type")==2 ? 0 : 1)
.ThenBy(r => r.Field<int>("Type"));

or probably better

table.AsEnumerable().
OrderBy(r => r.Field<int>("Type")==2 
   ? 0 
   : r => r.Field<int>("Type"))

or also elegant Tim Schmelter's solution

table.AsEnumerable()
.OrderByDescending(r => r.Field<int>("Type")==2)
.ThenBy(r => r.Field<int>("Type"))

Advantage or Tim Schmelter's solution : you're not depending on a "pseudo-value".

In the two first solutions, we assert that 0 is ((min possible value of the field) -1).

Is this real, can it change, we don't know.

Raphaël Althaus
  • 59,727
  • 6
  • 96
  • 122
  • 1
    Instead of pseeudocode i would add real code: `table.AsEnumerable().OrderByDescending(r => r.Field("Type")==2).ThenBy(r => r.Field("Type"))` – Tim Schmelter Sep 26 '12 at 15:08
  • This solution also works for a strings -> assume we are ordering alphabetically `.OrderBy(o => (o.Name == "ExceptionName" ? "0" : o.Name))` – qki Mar 12 '21 at 12:49
0

To make the sample simpler I removed the fact that we start from a DataTable, it's just a detail, and I thought we could do this:

var list = new [] { 1, 3, 5, 2, 4, 6, 9, 8 };
var sorters = new [] { 3, 2, -1 };

var o = from s in sorters
        from l in list.OrderBy(x => x)
        where s == l || (s == -1 && !sorters.Contains(l))
        select l;

The sort array contains the preferred sorters, this way we can have more than one if we need them, and then there is a 'jolly' (-1) to represent the end of the sorters. The jolly could be handled in a better way, it's like that just to give you the idea. At this point the algorithm is generic and does not need any hard-coded check on the preferred values (just the jolly).

There are some potential inefficiencies, but I just wanted to show the general idea of this solution, with some more works it could be done more efficiently.

Wasp
  • 3,395
  • 19
  • 37
0

Here you have like 5 ways of accomplishing this. It's a post regarding how to set value as the first of the order, then throw in the ones lower, and after the ones higher than the selected so if you have {1 2 3 4 5 6} and select item 4, output: {4 1 2 3 5 6}.. I prefer my own answer though.. ^_^

https://stackoverflow.com/a/12580121/920359

Community
  • 1
  • 1
specificityy
  • 580
  • 1
  • 5
  • 24