按名称空间排序列表

时间:2018-04-24 00:31:33

标签: c# list sorting

我想帮助排序特定列表。

想象一下以下列表:

antennas.sequence
antennas.ports
antennas.1.power
antennas.2.power
antennas.found
radio.modulation.1.set
radio.modulation.2.set
radio.transmit
radio.frequency

如果我们应用简单的List.Sort()函数,它将变为如下:

antennas.1.power
antennas.2.power
antennas.found
antennas.ports
antennas.sequence
radio.frequency
radio.modulation.1.set
radio.modulation.2.set
radio.transmit

但我正在寻找一种能够尊重命名空间数量的排序,因此深度较小的项目应该相互重叠。对于上面的例子,我希望列表的排序方式如下:

antennas.found
antennas.ports
antennas.sequence
antennas.1.power
antennas.2.power
radio.frequency
radio.transmit
radio.modulation.1.set
radio.modulation.2.set

1 个答案:

答案 0 :(得分:3)

我确信有一种更优雅的方式可以做到这一点,但是......

给定扩展程序

public static IOrderedEnumerable<string[]> RecusiveCustomOrderBy(this IOrderedEnumerable<string[]> list,int maxDepth, int depth = 1)
{
   if (depth >= maxDepth)
      return list;

   return list.ThenBy(x => x.Length <= depth ? null : x[depth])
              .ThenBy(x => x.Length)
              .RecusiveCustomOrderBy(maxDepth, depth + 1);
}

public static List<string> NamespaceOrderBy(this List<string> list)
{
   var split = list.Select(x => x.Split('.')).ToList();
   var maxDepth = split.Max(x => x.Length);

   return split.OrderBy(x => x[0])
               .ThenBy(x => x.Length)
               .RecusiveCustomOrderBy(maxDepth)
               .Select(x => string.Join(".", x))
               .ToList();
}

<强>用法

var list = new List<string>
   {
      "antennas.sequence",
      "antennas.ports",
      "antennas.1.power",
      "antennas.2.power",
      "antennas.found",
      "radio.modulation.1.set",
      "radio.modulation.2.set",
      "radio.transmit",
      "radio.frequency"
   };

var results = list.NamespaceOrderBy();

<强>输出

antennas.found
antennas.ports
antennas.sequence
antennas.1.power
antennas.2.power
radio.frequency
radio.transmit
radio.modulation.1.set
radio.modulation.2.set

Full Demo Here

  

注意:它可以用于一些简单的错误检查

相关问题