-2

I have a list with data that contains mixed numbers and strings, when i sort using

var list = thelist.OrderBy(p=>p.ColumnWithValues)

I would get results in the following order:

> 1, 1 item, 10, 2, 3, 4, 5, a, another 1, b

But i want them to be in the order below:

> 1, 2, 3, 4, 5, 10, 1 item,a, another 1, b

How would I go about doing this? I'm not even sure what to try with a list of multiple properties

update:

I've fixed my sample data, is what i'm looking to do possible?

Sam Jones
  • 4,443
  • 2
  • 40
  • 45

4 Answers4

3

You should sort by type first :

var list = thelist.OrderBy(p=> p.GetType() == typeof(string)).ThenBy(p => p)
Perfect28
  • 11,089
  • 3
  • 25
  • 45
1

Also try this.

var thelist = new[] {"1", "item", "10", "2", "3", "4", "5", "a", "b", "c"};
        var list = thelist.Where( num => num.All( x => char.IsDigit( x ) ) )
                  .OrderBy( r => { int z; int.TryParse( r, out z ); return z; } )
                  .Union( thelist.Where( str => str.All( x => !char.IsDigit( x ) ) )
                  .OrderBy( q => q ) );

         foreach (var i in list)
            {
                Console.WriteLine(i.ToString());

            }

And here is the .net fiddle to check...

Krishnraj Rana
  • 6,516
  • 2
  • 29
  • 36
0

Resolved by writing a class containing using IComparer

implemented by using:

thelist.OrderBy(p => p.ColumnWithValues, new OrdinalStringComparer());
Sam Jones
  • 4,443
  • 2
  • 40
  • 45
0
var list = thelist.OrderBy(p=> p.GetType() == typeof(string)).ThenBy(p => p)

Above is exactly working for me.

Actual list = { "(unknown)", "(unknown)", "(unknown)", 
                "183", "so", "Mo", "170", "Opps" , "(unknown)" }
Expected list = { "(unknown)", "(unknown)", "(unknown)", 
                  "(unknown)", "170","183", "Mo" ,"Opps", "so" }
perror
  • 7,071
  • 16
  • 58
  • 85