Sort list of class objects in c#

This question already has an answer here:

  • How to Sort a List<T> by a property in the object 19 answers

  • Using LINQ:

    tocke = tocke.OrderBy(x=> x.t.X).ToList();
    

    Make t public.


    Direct solution without LINQ (just list sorting, no additional list creation).

    Providing that t is made public:

      tocke.Sort((left, right) => left.t.X - right.t.X); 
    

    But the best way, IMHO, is to make class tocka comparable:

    class tocka: IComparable<tocka> {
      ...
    
      public int Compare(tocka other) {
        if (Object.RefrenceEquals(other, this))
          return 0;
        else if (Object.RefrenceEquals(other, null))
          return 1;
    
        return t.X - other.t.X; // <- Matthew Watson's idea
      }
    }
    
    // So you can sort the list by Sort:
    
    tocke.Sort();
    

    You can use LINQ, for instance like this:

    tocke.Sort( (x,y) => x.t.X.CompareTo(y.t.X) );
    

    but first you have to make t public, at least when getting it:

    public Point t { get; private set; }
    
    链接地址: http://www.djcxy.com/p/70940.html

    上一篇: 我如何通过每个对象的成员对对象列表进行排序?

    下一篇: 在c#中对类对象排序