Chad
Chad

Reputation: 24679

Using LINQ to sort a Class that inherits from LIST<TTYPE>

If I wanted to sort a a List where TType = Parameter,

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

        public string RunMonth { get; set; }

        public string CoverageMonth1 { get; set; }
   }

I would do this, for example.

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>();

What if I have a class, ParameterCollection, that inherits from List<Parameter>

        public class ParameterCollection : List<Parameter>
    {
            //handy properties added
    }

I get this error:

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

Is there a way to handle the casting to ParameterCollection in the LINQ statement?

Upvotes: 1

Views: 382

Answers (1)

StriplingWarrior
StriplingWarrior

Reputation: 156459

You'll need to create a new ParameterCollection to hold the elements in their new order.

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

Of course, you could make life easier for yourself by creating a constructor overload that passes into the List<> overload that takes an IEnumerable<> to start with.

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

You could even create an extension method off of IEnumerable<Parameter>.

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

You might also consider getting rid of ParameterCollection entirely, since using inheritance in this way is a bit of an antipattern.

Upvotes: 2

Related Questions