对ObservableCollection<>进行排序手动

时间:2012-06-25 14:18:28

标签: c# .net windows-phone-7 windows-phone-7.1 observablecollection

我在班级中关注ObservableCollection,我使用listbox应用程序中的该收藏夹将数据绑定到Windows phone 7

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;
        }
    }
}
}

现在我想根据myList

中的数据对EventDate进行排序

在所有情况下,EventDate中的数据将是以下之一

  1. 刚刚通过
  2. 昨天
  3. 明天
  4. 今天
  5. 日期//格式“MMM / dd”
  6. 自定义收藏必须按照上述顺序进行排序

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

    有可能吗?

3 个答案:

答案 0 :(得分:2)

由于您的CustomClass没有实现INotifyPropertyChange,我假设您只需要对insert进行排序(添加到集合时)。所以恕我直言,最容易做的事情(类似于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);
    }
}

答案 1 :(得分:1)

答案 2 :(得分:1)

你总是可以继承:

/// <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);