对混合整数和字符串列表进行排序

时间:2014-06-03 08:57:50

标签: c# sorting alphanumeric

当我使用

排序时,我有一个包含混合数字和字符串的数据列表
var list = thelist.OrderBy(p=>p.ColumnWithValues)

我会按以下顺序得到结果:

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

但我希望它们符合以下顺序:

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

我该怎么做呢?我甚至不确定尝试使用多个属性列表

更新

我修复了我的样本数据,这是我希望做的事情吗?

3 个答案:

答案 0 :(得分:3)

您应该先按类型排序:

var list = thelist.OrderBy(p=> p.GetType() == typeof(string)).ThenBy(p => p)

答案 1 :(得分:1)

也试试这个。

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());

            }

这是.net fiddle来检查......

答案 2 :(得分:0)

通过编写包含使用IComparer

的类来解决

使用以下方式实现:

thelist.OrderBy(p => p.ColumnWithValues, new OrdinalStringComparer());