我想编写一种排序逻辑,以将以下字符串排序为自定义类的输出:-
现在输出:- 3m_20,2m_20,1m_20,10d_20,5d_20,0d_20,0d_0,5d_0,10d_0,1m_0,2m_0,3m_0
必需的输出 0d_0,0d_20,5d_0,5d_20,10d_0,10d_20,1m_0,1m_20,2m_0,2m_20,3m_0,3m_20
我发现很难以上述方式进行复杂的排序。请帮我如何按要求排序?
我曾尝试根据IId与IComparable进行排序,但根据第一个字符对其进行排序。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
DateDefinition d1 = new DateDefinition { Horizon = "0d",Days=20};
DateDefinition d1_0 = new DateDefinition { Horizon = "0d",Days=0};
DateDefinition d2 = new DateDefinition { Horizon = "5d",Days=20};
DateDefinition d2_0 = new DateDefinition { Horizon = "5d",Days=0};
DateDefinition d3 = new DateDefinition { Horizon = "10d",Days=20};
DateDefinition d3_0 = new DateDefinition { Horizon = "10d",Days=0};
DateDefinition d4 = new DateDefinition { Horizon = "1m",Days=20};
DateDefinition d4_0 = new DateDefinition { Horizon = "1m",Days=0};
DateDefinition d5 = new DateDefinition { Horizon = "2m",Days=20};
DateDefinition d5_0 = new DateDefinition { Horizon = "2m",Days=0};
DateDefinition d6 = new DateDefinition { Horizon = "3m",Days=20};
DateDefinition d6_0 = new DateDefinition { Horizon = "3m",Days=0};
var definitions = new List<DateDefinition> {d6,d5,d4,d3,d2,d1,d1_0,d2_0,d3_0,d4_0,d5_0,d6_0};
definitions.Sort();
foreach(var d in definitions)
{
Console.WriteLine(d.Id);
}
}
}
public class DateDefinition : IComparable<DateDefinition>
{
public string Horizon { get; set; }
public int Days { get; set; }
public string Id
{
get { return Horizon + "_" + Days.ToString(); }
}
public int CompareTo(DateDefinition other)
{
if (ReferenceEquals(other, this)) return 0;
if(ReferenceEquals(other,null)) return -1;
return string.Compare(Id,other.Id, StringComparison.InvariantCultureIgnoreCase);
}
}
}
输出到上面的代码:-
0d_0 0d_20 10d_0 10d_20 1m_0 1m_20 2m_0 2m_20 3m_0 3m_20 5d_0 5d_20
需要像这样的输出:-
0d_0 0d_20 5d_0 5d_20 10d_0 10d_20 1m_0 1m_20 2m_0 2m_20 3m_0 3m_20
重要提示:在上述情况下,请注意d = days,m = months
答案 0 :(得分:1)
在CompareTo
方法中,您正在使用string.Compare
,因此它将按字母顺序比较两个实例的计算得出的ID属性。按字母顺序,“ 10d_0”在“ 5d_0”之前。
您想要进行某种数值比较,但是您将需要一些东西来将以月表示的Horizon值转换为以天表示的值(反之亦然)以进行有效的比较。
将Horizon属性定义为字符串似乎有点尴尬,因为它似乎包含数字和单位(d代表几天,m代表几个月)。您将需要解析它们并将其转换为数字,或者将Horizon重新定义为数字HorizonValue和字符串HorizonUnits。