按日期对ObservableCollection进行排序

时间:2012-05-29 12:04:51

标签: c#

我有一个集合

private ObservableCollection<ContentItemViewModel> _contentTree;
        public ObservableCollection<ContentItemViewModel> ContentTree
        {
            get { return _contentTree; }
        }

类ContentItemViewModel具有属性:

 private string _published;
        public string Published
        {
            get
            {
                return _published;
            }
            set
            {
                _published = value;

                NotifyPropertyChanged("Published");
            }
        }

即 - node.Published= Convert.ToDateTime(date.Value).ToString("dd MMM yyyy", new DateTimeFormatInfo());

我需要按日期排序ContentTree集合吗?我怎么能这样做?

2 个答案:

答案 0 :(得分:4)

我不知道是否有更好的方法,但你可以做到以下几点。这里的想法是在有序列表中创建一个有序列表和第一个foreach项,从内容树中删除并重新添加相关项。

var tempList = _contentTree.OrderBy(p => DateTime.Parse(p.DateAndTime)); 

tempList.ToList().ForEach(q =>
            {
                _contentTree.Remove(q);
                _contentTree.Add(q);
            });

或者您可以使用比较;

Comparison<ContentItemViewModel> comparison = new Comparison<ContentItemViewModel>(
            (p,q) =>
            {
                DateTime first = DateTime.Parse(p.DateAndTime);
                DateTime second = DateTime.Parse(q.DateAndTime);
                if (first == second)
                    return 0;
                if (first > second)
                    return 1;
                return -1;
            });


        List<ContentItemViewModel> tempList = _contentTree.ToList();
        tempList.Sort(comparison);
        _contentTree = new ObservableCollection<ContentItemViewModel>(tempList);

答案 1 :(得分:0)

您可以使用此:

ConceptItems = new ObservableCollection<DataConcept>(ConceptItems.OrderBy(i => i.DateColumn));