Linq - 按编号排序然后是字母

时间:2011-02-25 18:12:36

标签: c# linq

我有一个字符串列表,这些字符串包含数字和单词。

我想要做的是按数字(数字顺序)和单词(字母顺序)命令

我的列表中没有两者的混合...这是一个例子

  

1,5,500,LT,RT,400 - > LINQ - > 1,   5,400,500,LT,RT

以下是我所拥有的一个例子,它有效,但我想知道是否有更好的写作方式?

            int results = 0;
            // Grabs all voltages
            var voltage = ActiveRecordLinq.AsQueryable<Equipment>()
                .OrderBy(x => x.Voltage)
                .Select(x => x.Voltage)
                .Distinct()
                .ToList();
            // Order by numeric
            var numberVoltage = voltage
                .Where( x => int.TryParse(x, out results))
                .OrderBy( x => Convert.ToInt32(x));
            // Then by alpha
            var letterVoltage = voltage
                .Where(x=> !String.IsNullOrEmpty(x))
                .Where(x => !int.TryParse(x, out results))
                .OrderBy(x => x);

            return numberVoltage.Union(letterVoltage)

感谢您的帮助!

2 个答案:

答案 0 :(得分:18)

鉴于你正在进行所有进程(因为你有一个ToList调用)我想我只是使用自定义比较器:

return ActiveRecordLinq.AsQueryable<Equipment>()
                       .Select(x => x.Voltage)
                       .Distinct()
                       .AsEnumerable() // Do the rest in-process
                       .Where(x => !string.IsNullOrEmpty(x))
                       .OrderBy(x => x, new AlphaNumericComparer())
                       .ToList();

AlphaNumericComparer实施IComparer<string>的地方,如下所示:

public int Compare(string first, string second)
{
    // For simplicity, let's assume neither is null :)

    int firstNumber, secondNumber;
    bool firstIsNumber = int.TryParse(first, out firstNumber);
    bool secondIsNumber = int.TryParse(second, out secondNumber);

    if (firstIsNumber)
    {
        // If they're both numbers, compare them; otherwise first comes first
        return secondIsNumber ? firstNumber.CompareTo(secondNumber) : -1;
    }
    // If second is a number, that should come first; otherwise compare
    // as strings
    return secondIsNumber ? 1 : first.CompareTo(second);
}

可以在后一部分使用巨大的条件:

public int Compare(string first, string second)
{
    // For simplicity, let's assume neither is null :)

    int firstNumber, secondNumber;
    bool firstIsNumber = int.TryParse(first, out firstNumber);
    bool secondIsNumber = int.TryParse(second, out secondNumber);

    return firstIsNumber 
        ? secondIsNumber ? firstNumber.CompareTo(secondNumber) : -1;
        : secondIsNumber ? 1 : first.CompareTo(second);
}

......但在这种情况下,我认为我不会:)

答案 1 :(得分:6)

此解决方案尝试为每个值解析一次。

List<string> voltage = new List<string>() { "1", "5", "500" , "LT", "RT", "400" };

List<string> result = voltage
  .OrderBy(s =>
  {
    int i = 0;
    return int.TryParse(s, out i) ? i : int.MaxValue;
  })
  .ThenBy(s => s)
  .ToList();