2

I know that by implementing IComparable on a class, like…

public class Person : IComparable<Person>
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public int CompareTo(Person other)
    {
        var val = LastName.CompareTo(other.LastName);
        return val == 0 ? FirstName.CompareTo(other.FirstName) : val;
    }
}

…allows me to call

IEnumerable.OrderBy(x => x.Person);

…instead of

IEnumerable.OrderBy(x => x.Person.LastName)
           .ThenBy(x => x.Person.FirstName);

How would I be able to do the same with an IQueryable.OrderBy in LINQ To SQL on a Person Entity?

  • 1
    LINQ would need to generate SQL code and in SQL you have to `oder by lastname, firstname` there is no other way in SQL – Krish Nov 23 '18 at 20:53
  • One alternative that could be considered is using a reusable expression as suggested [here](https://stackoverflow.com/questions/18692381/is-it-possible-to-use-icomparable-to-compare-entities-in-entity-framework#comment27604565_18692439). But, yeah, I think LINQ-to-SQL (or any ORM) isn't smart enough to convert 'arbitrary' C# into SQL... – Collin Barrett Nov 26 '18 at 21:03

1 Answers1

-1

Try doing something like this:

IEnumerable.OrderBy(x => strig.Fromat("{0}{1}", x.Person.LastName, x.Person.FirstName);

or (if you are using the newer C# version where $ is supported):

IEnumerable.OrderBy(x => $"{x.Person.LastName}{x.Person.FirstName}");

It should sort your items by taking in to account both the last name and the first name (and on the way gaining some performance by iterating only once on the list).

Hope it helps!

Itay Podhajcer
  • 2,616
  • 2
  • 9
  • 14
  • 1
    This is a bad idea. First, it will sort wrongly as persons can have multiple last names and first names and your code doesn’t distinguish between both. There may also be several other cases where mushing first and last names together would yield different results than handling them separately. Second, OP explicitly asked for Queryable and I find it unlikely the SQL query provider would parse the string.Format expression tree to convert it to a SQL expression. Third, why are you even using string.Format just to concatenation two strings? – ckuri Nov 24 '18 at 22:23