Click here to Skip to main content
15,897,519 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have List of `Person` class as

var list = List<person>();

I want to order the list in descending order based on `PersonId`

var newlist = list.OrderByDescending(x => x.PersonId).ToList();

The class `Person` is created some other team and I don't want change the class by implementing `IComparable`.

Is there any way that I can use order by without implementing `IComparable`.

Any help?

What I have tried:

var newlist = list.OrderByDescending(x => x.PersonId).ToList();
Posted
Updated 6-Dec-17 2:06am
Comments
F-ES Sitecore 6-Dec-17 6:47am    
Your code should work, you don't need Person to implement IComparable.

1 solution

The problem is not the Person class, it's the type of PersonId: if it's integer, that'll work fine:
class Program
    {
    static void Main(string[] args)
        {
        var list = new List<Person>();
        list.Add(new Person(){PersonId = 3});
        list.Add(new Person(){PersonId = 7});
        list.Add(new Person(){PersonId = 9});
        list.Add(new Person(){PersonId = 42});
        var newlist = list.OrderByDescending(x => x.PersonId).ToList();
        Console.ReadLine();
        }
    }
class Person
    {
    public int PersonId {get; set; }
    }
But if the PersonId isn't IComparable there is no real way to be sure that the ordering is correct, other than arranging a comparator. But you won't get an error even like this:
class Program
    {
    static void Main(string[] args)
        {
        var list = new List<Person>();
        list.Add(new Person(){PersonId = 3});
        list.Add(new Person(){PersonId = 7});
        list.Add(new Person(){PersonId = 9});
        list.Add(new Person(){PersonId = 42});
        var newlist = list.OrderByDescending(x => x.p).ToList();
        Console.ReadLine();
        }
    }
class Person
    {
    public int PersonId {get; set; }
    public Person p { get; set; }
    }
}
You'll just get the same order you started with, probably.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900