订购清单 包含模板中的关键字c#

问题描述 投票:0回答:1

我有个问题。我需要根据模板订购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

有什么可以帮助我吗?

c# string list
1个回答
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());
© www.soinside.com 2019 - 2024. All rights reserved.