Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/257.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用特殊规则对字符串集合进行排序_C#_String_Linq_Sorting_Collections - Fatal编程技术网

C# 使用特殊规则对字符串集合进行排序

C# 使用特殊规则对字符串集合进行排序,c#,string,linq,sorting,collections,C#,String,Linq,Sorting,Collections,前言:我在工作中偶然发现了这个问题,并认为这是一个有趣的问题 前言编辑:我们已经有了一个可行的解决方案,但我正在寻找其他方法来解决这个问题 给定一组字符串: ["2015", "2016 New", "2016 Used", "2017 New", "2017 Used", "2018"] 我想按年份降序排列这个集合 但是,我还想应用一个特殊规则,其中包含字符串“New”的年份必须早于包含字符串“Used”的年份 预期结果: ["2018", "2017 New", "2017 Used",

前言:我在工作中偶然发现了这个问题,并认为这是一个有趣的问题

前言编辑:我们已经有了一个可行的解决方案,但我正在寻找其他方法来解决这个问题


给定一组
字符串

["2015", "2016 New", "2016 Used", "2017 New", "2017 Used", "2018"]
我想按年份降序排列这个集合

但是,我还想应用一个特殊规则,其中包含字符串
“New”
的年份必须早于包含字符串
“Used”
的年份

预期结果:

["2018", "2017 New", "2017 Used", "2016 New", "2016 Used", "2015"]

假设:

  • 如果集合包含一个包含
    “New”
    的给定年份字符串,则集合将始终包含包含
    “Used”
    的同一年份(反之亦然),并且不会单独包含年份

    ["2017 New", "2017", "2016 Used", "2016"] // invalid input
    
  • 年份将在1000-9999之间


解决此问题的最佳方法是什么?


编辑

以下是我们的解决方案:

var l = new[] { "2015", "2016 New", "2016 Used", "2017 New", "2017 Used", "2018" };

var sorted = l.OrderByDescending(i => i.Replace("Used", "Ased")).ToArray();
// ["2018", "2017 New", "2017 Used", "2016 New", "2016 Used", "2015"]

我会分割你的字符串,并使用这些部分进行排序

var inputx = new string[] { "2015", "2016 New", "2016 Used", "2017 New", "2017 Used", "2018" };

var outputx = inputx.OrderByDescending(x => x.Split()[0]).ThenBy(x=>x).ToArray();
要在
“2017”
之前获得
“2017新”
,以及在
“2017已使用”
之前获得
“2017”

或者就地排序可能更有效一些:

Array.Sort(arr, (a, b) => b.Split()[0].CompareTo(a.Split()[0]) + 
                    b.EndsWith(" New").CompareTo(a.EndsWith(" New")));

“2017 New”将始终位于“2017 Used”之前,因此您可以通过默认排序对其进行简单排序。您是否尝试过任何操作?我们不做你的工作。@Fabio是的,但OP想按降序排序。因此,使用默认排序时,它将是
2018、2017已使用、2017新等
“我们最终得到了预期结果。”那么问题是什么呢?排序+自定义排序=
i可比较
Array.Sort(arr, (a, b) => b.Split()[0].CompareTo(a.Split()[0]) + 
                    b.EndsWith(" New").CompareTo(a.EndsWith(" New")));