Thursday, February 17, 2011

How do I use 'Order By' to sort on a property of an inherited type in LINQ-to-SQL?

Hi,

I have a fairly standard inheritance situation in my current LINQ-to-SQL project. I have a base class called 'Party' and classes called 'Individual' and 'Organisation' which inherit from it.

What I want to achieve seems (and probably is) fairly simple. I want to return a list of 'Organisations' sorted by Company Name. The problem is that the company name ('CoName') field is a member of the 'Organisation' class, not the 'Party' class.

My current, unsorted query is...

oClients = (From P In ERM.Parties Where TypeOf (P) Is Organisation)

What I'd like to do is this...

oClients = (From P In ERM.Parties Where TypeOf (P) Is Organisation Order By CoName)

... but of course this doesn't work as the 'CoName' property isn't a member of the 'Party' class.

Any help would be greatly appreciated!

From stackoverflow
  • Use the OfType<>() operator:

    ERM.Parties.OfType<Organisation>().OrderBy(p => p.CoName)
    
    David B : It's more of a method than an operator. But yes.

0 comments:

Post a Comment