如何使用自定义比较器在C#中按字母顺序对元素进行排序

时间:2019-02-10 11:37:59

标签: c#

我是C#的新手。我正在尝试编写一个自定义比较器,该比较器按城市名称的字母顺序对CityInfo对象的列表进行排序。

 public class CityInfoComparer 
    {
        private readonly IComparer<string> _baseComparer;

        public CityInfoComparer(IComparer<string> baseComparer) 
        {
            _baseComparer = baseComparer;
        }

        public int Compare(CityInfo city1, CityInfo city2)
        {
            return _baseComparer.Compare(city1.CityName, city2.CityName);

        }
    }


public class CityList
    {
        public List<CityInfo> CityInfos { get; set; }

        public void Sort(CityInfo city1, CityInfo city2)
        {
            CityInfos.Sort(new CityInfoComparer(StringComparer.CurrentCulture));

            //CityInfos.Sort()
        }

    }

此行出现错误:

CityInfos.Sort(new CityInfoComparer(StringComparer.CurrentCulture));

无法从CityInfo转换为Systems.Generic.Collections.Icomparer

1 个答案:

答案 0 :(得分:1)

您应该继承自IComparer,请参见下文:

easeLinearity