列表与LT的自定义排序; T> [英] Custom Sorting of List<T>

查看:130
本文介绍了列表与LT的自定义排序; T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表< T> ,其中 T 是我的事件有型的字段时间类型。这份名单是从web服务填充,如果事件没有一个时间,将该值设置为0。

I have a List<T> where T is my Event type which has a field time of type long. This list is populated from a web service and if an event doesn't have a time, the value set is 0.

我想要做的排序是我的名单升序按时间,但放置物品与最底部时间= 0。

What i want to do is sort my list ascending by time, but place the items with time=0 at the very bottom.

目前,我在一个黑客某种时尚的完成这一点,我想学一种更好的方法

Currently I am accomplishing this in a hack sort of fashion and I want to learn a better way.

var events = new ObservableCollection<Event>();
var resp = JsonConvert.DeserializeObject<Events>(restResponse.Content).Items;

var notime = resp.Where(r => r.time == 0);
var yestime = resp.Where(r => r.time > 0);

yestime.ToList().ForEach(events.Add);
notime.ToList().ForEach(events.Add);

CallbackInternal(callback, events);



我试图实现自定义的的IComparer ,但没有工作这么好(这里是一杆吧)

I attempted implementing a custom IComparer, but that didn't work out so well (here is one shot at it)

public class EventComparer : IComparer<Event>
{
    public int Compare(Event x, Event y)
    {
        if (x.time == 0) return 0;
        if (x.time < y.time) return -1;
        if (x.time > y.time) return 1;
        return 0;
    }
}



指导赞赏!

guidance is appreciated!

谢谢!

推荐答案

尝试

   events.OrderBy (e => e.Time == 0).ThenBy (e => e.Time);

这篇关于列表与LT的自定义排序; T&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆