我有下面的
..。我需要
排序
这是按字母顺序排列的。
private ObservableCollection _animals = new ObservableCollection
{
"Cat", "Dog", "Bear", "Lion", "Mouse",
"Horse", "Rat", "Elephant", "Kangaroo", "Lizard",
"Snake", "Frog", "Fish", "Butterfly", "Human",
"Cow", "Bumble Bee"
};
我试过了
..。但是我不知道如何正确使用它。
_animals.OrderByDescending(a => a.);
我该怎么做呢?
发布于 2016-04-15 17:07:09
我知道这是一个老生常谈的问题,但这是谷歌“排序可观察收集”的第一个结果,所以我认为值得留下我的两美分。
方法
我的方法是构建一个
从
,对其进行排序(通过其
方法,
有关msdn的更多信息
当
已排序,请重新排序
使用
方法。
代码
public static void Sort(this ObservableCollection collection, Comparison comparison)
{
var sortableList = new List(collection);
sortableList.Sort(comparison);
for (int i = 0; i < sortableList.Count; i++)
{
collection.Move(collection.IndexOf(sortableList[i]), i);
}
}
测试
public void TestObservableCollectionSortExtension()
{
var observableCollection = new ObservableCollection();
var maxValue = 10;
// Populate the list in reverse mode [maxValue, maxValue-1, ..., 1, 0]
for (int i = maxValue; i >= 0; i--)
{
observableCollection.Add(i);
}
// Assert the collection is in reverse mode
for (int i = maxValue; i >= 0; i--)
{
Assert.AreEqual(i, observableCollection[maxValue - i]);
}
// Sort the observable collection
observableCollection.Sort((a, b) => { return a.CompareTo(b); });
// Assert elements have been sorted
for (int i = 0; i < maxValue; i++)
{
Assert.AreEqual(i, observableCollection[i]);
}
}
备注
这只是一个概念证明,展示了如何对
在不破坏items.The绑定的情况下,排序算法有改进和验证的空间(如所指出的索引检查
这里
)。
发布于 2016-08-20 00:24:25
我看了看这些,我正在对它进行排序,然后它打破了绑定,如上所述。想出了这个解决方案,虽然比你的大多数解决方案简单,但它似乎做了我想做的,
public static ObservableCollection OrderThoseGroups( ObservableCollection orderThoseGroups)
{
ObservableCollection temp;
temp = new ObservableCollection(orderThoseGroups.OrderBy(p => p));
orderThoseGroups.Clear();
foreach (string j in temp) orderThoseGroups.Add(j);
return orderThoseGroups;
}
发布于 2017-04-25 21:57:38
我为ObservableCollection创建了一个扩展方法
public static void MySort(this ObservableCollection observableCollection, Func keySelector)
{
var a = observableCollection.OrderBy(keySelector).ToList();
observableCollection.Clear();
foreach(var b in a)
{
observableCollection.Add(b);
}
}
它似乎可以工作,并且您不需要实现IComparable
https://stackoverflow.com/questions/19112922
复制相似问题