使用LINQ对继承自LIST <ttype>的类进行排序

时间:2016-06-21 19:24:51

标签: c# linq

如果我想对一个列表进行排序,其中TType = Parameter,

    public class Parameter
    {
        public string VendorId { get; set; }

        public string RunMonth { get; set; }

        public string CoverageMonth1 { get; set; }
   }

我会这样做,例如。

List<Models.Parameter> ps = new List<Models.Parameter>()
{
        new Models.Parameter() { EffectiveDate = new DateTime(2016, 1, 1) }
        ,new Models.Parameter() { EffectiveDate = new DateTime(2014, 1, 1) }
};

ps = ps.OrderBy(p => p.EffectiveDate).ToList<Models.Parameter>();

如果我有一个继承自List<Parameter>

的类ParameterCollection,该怎么办?
        public class ParameterCollection : List<Parameter>
    {
            //handy properties added
    }

我收到此错误:

ParameterCollection parameterCollection;    
parameterCollection = parameterCollection.OrderBy(parameter => parameter.EffectiveDate);

Severity    Code    Description Project File    Line    Category    Suppression State
Error   CS0266  Cannot implicitly convert type 'System.Linq.IOrderedEnumerable<StateAssessment.Models.Parameter>' to 'StateAssessment.Models.ParameterCollection'. An explicit conversion exists (are you missing a cast?)  StateAssessment.Services    C:\Workspace\Healthcare-Finance_IT\Main\WebApps\StateAssessment\StateAssessment.Services\Parameter.cs   32  Compiler    Active

有没有办法在LINQ语句中处理对ParameterCollection的转换?

1 个答案:

答案 0 :(得分:1)

您需要创建一个新的ParameterCollection来按新顺序保存元素。

var ps2 = new ParameterCollection();
ps2.AddRange(ps.OrderBy(p => p.EffectiveDate));
ps = ps2;

当然,你可以通过创建一个构造函数重载来让自己更轻松,这个重载会进入List<>重载,开始IEnumerable<>

ps = new ParameterCollection(ps.OrderBy(p => p.EffectiveDate));

您甚至可以从IEnumerable<Parameter>创建扩展方法。

ps = ps.OrderBy(p => p.EffectiveDate).ToParameterCollection();

你也可以考虑完全摆脱ParameterCollection,因为以这种方式使用继承有点像反模式。