连续对int进行排序

时间:2019-05-08 14:17:22

标签: c# sorting

鉴于List<int>之类的{ 1, 1, 1, 2, 2, 2, 3, 3, 3, 4 },我想获得{ 1, 2, 3, 4, 1, 2, 3, 1, 2, 3 }。我有一个有效的代码,但我想找到一种更优雅/更整洁的方式来解决此问题。

var list = new List<int>() { 1, 1, 1, 2, 2, 2, 3, 3, 3, 4 };
var sortedList = new List<int>();
var set = new HashSet<int>();

while (list.Count > 0)
{
    foreach (var l in list)
    {
        set.Add(l);
    }
    sortedList.AddRange(set);

    foreach(var s in set)
    {
        list.Remove(s);
    }
    set.Clear();
}

// sortedList -> {1, 2, 3, 4, 1, 2, 3, 1, 2, 3}

1 个答案:

答案 0 :(得分:4)

您可以尝试 Linq ;首先,我们将初始的list分成组

  {1, 1, 1}
  {2, 2, 2}
  {3, 3, 3}
  {4}

然后枚举这些组中的项目-{{1, 2, 3, 4}, {1, 2, 3}, {1, 2, 3}}并将其展平:{1, 2, 3, 4, 1, 2, 3, 1, 2, 3}。让我们将其提取为一种方法:

代码:

private static List<int> MySort(IEnumerable<int> list) {
  var groups = list
   .GroupBy(item => item)
   .Select(chunk => new {
     value = chunk.Key,
     count = chunk.Count()
   })
   .OrderBy(item => item.value)
   .ToArray();

  int maxCount = groups.Max(group => group.count);

  return Enumerable
    .Range(0, maxCount)
    .SelectMany(i => groups
       .Where(chunk => chunk.count > i)
       .Select(chunk => chunk.value))
    .ToList();
}

演示:

List<int>[] tests = new List<int>[] {
  new List<int>() { 1, 1, 1, 2, 2, 2, 3, 3, 3, 4 },
  new List<int>() { 1, 1, 1, 3, 4, 4, 4, 4, 4, 5, 10 },
};

var demo = string.Join(Environment.NewLine, tests
  .Select(test => $"{string.Join(", ", test),-35} -> {string.Join(", ", MySort(test))}"));

Console.Write(demo);

结果:

1, 1, 1, 2, 2, 2, 3, 3, 3, 4        -> 1, 2, 3, 4, 1, 2, 3, 1, 2, 3
1, 1, 1, 3, 4, 4, 4, 4, 4, 5, 10    -> 1, 3, 4, 5, 10, 1, 4, 1, 4, 4, 4