繁体   English   中英

手动排序ObservableCollection <>

[英]Sorting ObservableCollection<> manually

我在班级里遵循ObservableCollection ,我正在Windows phone 7应用程序中使用该Collection将数据绑定到listbox

public ObservableCollection<CustomClass> myList = new ObservableCollection<CustomClass>();

我的自定义课程

public class CustomClass
{
public string Id { get; set; }        
public string Name { get; set; }        
public string EventName { get; set; }        
public string EventDate get
{
    return EventDate;
}
set
{
    if (value != null)
    {
        DateTime eventDate = DateTime.Parse(value);
        int today = DateTime.Now.Day;
        if (eventDate.Day <= today + 1 & eventDate.Day >= today - 2)
        {
            if (eventDate.Day == today)
            EventDate = "Today";
            else if (eventDate.Day == (today + 1))
            EventDate = "Tomorrow";
            else if (eventDate.Day == (today - 1))
            EventDate = "Yesterday";
            else if (eventDate.Day >= (today - 2))
            EventDate = "Just Passed";
        }
        else
        {
            EventDate = value;
        }
    }
}
}

现在我想根据EventDate的数据对myList进行排序

在所有情况下,EventDate中的数据均为以下之一

  1. 刚刚通过
  2. 昨天
  3. 明天
  4. 今天
  5. 日期//格式为“ MMM / dd”

自定义收藏只能按上述顺序排序

我从不同来源获取数据,因此在将数据绑定到集合中时无法进行排序

可能吗??

由于您的CustomClass没有实现INotifyPropertyChange,因此我假设您只需在插入时排序(添加到集合时)。 因此,恕我直言,最容易做的事情(类似于RandolfRincón-Fadul的解决方案)是子类化,然后重写Add方法。

public class ComparingObservableCollection<T> : ObservableCollection<T>
     where T : IComparable<T>
{

    protected override void InsertItem(int index, T item)
    {
        int i = 0;
        bool found = false;
        for (i = 0; i < Items.Count; i++)
        {
            if (item.CompareTo(Items[i]) < 0) {
                found = true;
                break;
            }
        }

        if (!found) i = Count;

        base.InsertItem(i, item);
    }
}

然后,您要做的就是在CustomClass上实现IComparable<CustomClass> ,如下所示:

public class CustomClass : IComparable<CustomClass>
{
public string Id { get; set; }        
public string Name { get; set; }        
public string EventName { get; set; }        
public string EventDate { get
{
    return EventDate;
}
set
{
    if (value != null)
    {
        DateTime eventDate = DateTime.Parse(value);
        int today = DateTime.Now.Day;
        if (eventDate.Day <= today + 1 & eventDate.Day >= today - 2)
        {
            if (eventDate.Day == today)
            EventDate = "Today";
            else if (eventDate.Day == (today + 1))
            EventDate = "Tomorrow";
            else if (eventDate.Day == (today - 1))
            EventDate = "Yesterday";
            else if (eventDate.Day >= (today - 2))
            EventDate = "Just Passed";
        }
        else
        {
            EventDate = value;
        }
    }
}
    private int Order { get {
       switch(EventDate) {
         case "Just Passed": return 1;
         case "Yesterday": return 2;
         case "Tomorrow": return 3;
         case "Today": return 4;
         default: return 5;
       }
    }
    }

    public int CompareTo(CustomClass other) {
       return this.Order.CompareTo(other.Order);
    }
}

您可以始终子类化:

/// <summary>
/// Represents a dynamic data collection that provides notifications when items get added, removed, or when the whole list is refreshed and allows sorting.
/// </summary>
/// <typeparam name="T">The type of elements in the collection.</typeparam>
public class SortableObservableCollection<T> : ObservableCollection<T>
{
    /// <summary>
    /// Sorts the items of the collection in ascending order according to a key.
    /// </summary>
    /// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector"/>.</typeparam>
    /// <param name="keySelector">A function to extract a key from an item.</param>
    public void Sort<TKey>(Func<T, TKey> keySelector)
    {
        InternalSort(Items.OrderBy(keySelector));
    }

    /// <summary>
    /// Sorts the items of the collection in ascending order according to a key.
    /// </summary>
    /// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector"/>.</typeparam>
    /// <param name="keySelector">A function to extract a key from an item.</param>
    /// <param name="comparer">An <see cref="IComparer{T}"/> to compare keys.</param>
    public void Sort<TKey>(Func<T, TKey> keySelector, IComparer<TKey> comparer)
    {
        InternalSort(Items.OrderBy(keySelector, comparer));
    }

    /// <summary>
    /// Moves the items of the collection so that their orders are the same as those of the items provided.
    /// </summary>
    /// <param name="sortedItems">An <see cref="IEnumerable{T}"/> to provide item orders.</param>
    private void InternalSort(IEnumerable<T> sortedItems)
    {
        var sortedItemsList = sortedItems.ToList();

        foreach (var item in sortedItemsList)
        {
            Move(IndexOf(item), sortedItemsList.IndexOf(item));
        }
    }
}

然后使用lambda表达式排序

((SortableObservableCollection<CustomClass>)MyList).Sort(s => s.EventDate);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM