订购列表<string>,其中包含模板中的关键字c#

时间:2018-02-28 09:47:39

标签: c# string list

我有问题。我需要根据模板订购C#List<string>,但模板只包含字符串的一部分,因此它必须是Contains()。 模板类似于:

House
Vehicle
Electric

和输入类似:

Electric bike
Household appliances
Electricity
Electric generator
Vehicle appliances

并且有序列表应该是:

Household appliances
Vehicle appliances
Electric bike
Electricity
Electric generator

有什么可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

您必须实现自定义比较器

public class CustomStringComparer : IComparer<string>
{
    List<string> templates = new List<string> { "House", "Vehicle", "Electric" };
    public int Compare(string x, string y)
    {
        string xTemplate = templates.FirstOrDefault(t => x.Contains(t));
        string yTemplate = templates.FirstOrDefault(t => y.Contains(t));
        int xTemplateIndex = templates.IndexOf(xTemplate);
        int yTemplateIndex = templates.IndexOf(yTemplate);
        return xTemplateIndex.CompareTo(yTemplateIndex);
    }
}

然后你可以把这个比较器传递给Sort()

List<string> input = new List<string>
{
    "Electric bike",
    "Household appliances",
    "Electricity",
    "Electric generator",
    "Vehicle appliances"
};

input.Sort(new CustomStringComparer());