Custom Sorting of List

前端 未结 5 861
清酒与你
清酒与你 2021-01-21 03:11

I have a List where T is my Event type which has a field time of type long. This list is populated from

相关标签:
5条回答
  • 2021-01-21 03:24

    Try

       events.OrderBy (e => e.Time == 0).ThenBy (e => e.Time);
    
    0 讨论(0)
  • 2021-01-21 03:25

    You could use LINQ:

    resp.OrderBy(i => i.time == 0 ? int.MaxValue : i.time);
    
    0 讨论(0)
  • 2021-01-21 03:31

    Your custom IComparer is incorrect. With correct logic, it should work just fine. The problem is that if the left value is zero, any value will be equal to it. This means that 0 == 3 is true, and 3 > 0 is true. In fact, 0 > 3 and 3 < 0 should be true

    You should do something like this instead:

    if (x.time == y.time) return 0;
    if (x.time == 0) return 1;
    if (y.time == 0) return -1;
    return x.time.CompareTo(y.time);
    
    0 讨论(0)
  • 2021-01-21 03:38

    You should do something like this:

     if(x.time==y.time) return 0;
     if(x.time==0) return 1;
     return x.time - y.time;
    

    The point here is that 0 is larger than any other time, so it'll be placed at the end of the list.

    0 讨论(0)
  • 2021-01-21 03:40

    Try this one (you have to adjust it for your needs):

        class Comparer : IComparer<int>
        {
            public int Compare(int x, int y)
            {
                if (x == y) return 0;
                else if (x == 0) return 1;
                else if (y == 0) return -1;
                else if (x < y) return -1;
                else if (x > y) return 1;
            }
        }
    
    0 讨论(0)
提交回复
热议问题