using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
namespace ServerManagerTool.Common.Model
{
///
/// Represents a dynamic data collection that provides notifications when items get added, removed, or when the whole list is refreshed and allows sorting.
///
/// The type of elements in the collection.
public class SortableObservableCollection : ObservableCollection
{
public SortableObservableCollection()
{
}
public SortableObservableCollection(List list)
: base(list)
{
}
public SortableObservableCollection(IEnumerable collection)
: base(collection)
{
}
///
/// Sorts the items of the collection in ascending order according to a key.
///
/// The type of the key returned by .
/// A function to extract a key from an item.
public void Sort(Func keySelector)
{
InternalSort(Items.OrderBy(keySelector));
}
///
/// Sorts the items of the collection in ascending order according to a key.
///
/// The type of the key returned by .
/// A function to extract a key from an item.
/// An to compare keys.
public void Sort(Func keySelector, IComparer comparer)
{
InternalSort(Items.OrderBy(keySelector, comparer));
}
///
/// Sorts the items of the collection in descending order according to a key.
///
/// The type of the key returned by .
/// A function to extract a key from an item.
public void SortDescending(Func keySelector)
{
InternalSort(Items.OrderByDescending(keySelector));
}
///
/// Sorts the items of the collection in descending order according to a key.
///
/// The type of the key returned by .
/// A function to extract a key from an item.
/// An to compare keys.
public void SortDescending(Func keySelector, IComparer comparer)
{
InternalSort(Items.OrderByDescending(keySelector, comparer));
}
///
/// Moves the items of the collection so that their orders are the same as those of the items provided.
///
/// An to provide item orders.
private void InternalSort(IEnumerable sortedItems)
{
var sortedItemsList = sortedItems.ToList();
foreach (var item in sortedItemsList)
{
Move(IndexOf(item), sortedItemsList.IndexOf(item));
}
}
}
}