0

When sorting a column on my WebGrid from A to Z, the empty strings always come up first, so I have :

""
""
"A"
"B"

(Without the quotes of course).

I want them to come up last, is there a simple way to do this ?

chridam
  • 100,957
  • 23
  • 236
  • 235
deonclem
  • 860
  • 10
  • 25
  • 4
    Quick way would be remove them from the list, sort list, and then add them at the back. Better way would be implement your own `IComparer` and pass it to the sorting method – 3dd Jun 19 '14 at 09:45
  • I agree with @3dd. if I remember correctly, alphabetical sort order goes in order of special characters, numbers, alphanumeric. – user3036342 Jun 19 '14 at 10:59
  • When sorting with LINQ you could use something like `x.OrderBy(s => s == "" ? 1 : 0).ThenBy(s => s)` – CodesInChaos Jun 19 '14 at 11:28
  • 1
    But how can I specify my own sorting method to the WebGrid ? So far I just tell it which column should be used to do the sorting. How can I replace its sorting method which I cannot access by mine ? – deonclem Jun 19 '14 at 12:45
  • @CodesInChaos Given that the `bool` type is in itself `IComparable<>`, I would not use the conditional operator `?:` there, so it would be `x.OrderByDescending(s => s != "").ThenBy(s => s)` or equivalently `x.OrderBy(s => s == "").ThenBy(s => s)`. You could also want `x.OrderBy(string.IsNullOrEmpty).ThenBy(s => s)` where a named method is used instead of an anonymous one. – Jeppe Stig Nielsen Jun 19 '14 at 12:45
  • @JeppeStigNielsen I know you can do that since `false.CompareTo(true) < 0` matching the underlying 0 vs. 1 integers. But I think that using this ordering makes the code harder to read since there is no logical ordering on booleans. – CodesInChaos Jun 19 '14 at 12:51

1 Answers1

2

you should sort with generic Comparison delegate like this one:

private int MyComparison(string x, string y)
    {
        if (string.IsNullOrEmpty(x))
        {
            if (string.IsNullOrEmpty(y))
            {
                // If x is null and y is null, they're 
                // equal.  
                return 0;
            }
            else
            {
                // If x is null and y is not null, y 
                // is greater.  
                return 1;
            }
        }
        else
        {
            // If x is not null... 
            // 
            if (string.IsNullOrEmpty(y))
            // ...and y is null, x is greater.
            {
                return -1;
            }
            //sort them with ordinary string comparison
            else
                return x.CompareTo(y);
        }
    }

List<string> liststring = new List<string>() {"C", "","A","","B"};
liststring.Sort(MyComparison);
  • But how can I use this kind of method instead of the webgrid's default one ? I can use `autoSortAndPage: false` with the `Bind()` method but obviously that disables the pagination as well, and I don't want to rewrite the entire webgrid class. – deonclem Jun 19 '14 at 13:04