示例类:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public bool IsWoman { get; set; }
}
1、转换成List列表,使用lambada,排序后再重新添加到ObservableColletion集合
ObservableCollection<Person> peoples = new ObservableCollection<Person>
{
new Person { Name = "Alice", IsWomen = true },
new Person { Name = "Bob", IsWomen = false },
new Person { Name = "Charlie", IsWomen = false },
new Person { Name = "Diana", IsWomen = true }
};
//以名称排序
var List<People> peopleList = peoples.ToList();
peopleList.Sort((x,y) => x.Name.CompareTo(y.Name));
peoples.Clear();
foreach (var people in peopleList)
{
peoples.Add(people);
}
2、使用Comparer类,并使用扩展方法
编写排序扩展方法:
/// <summary>
/// 排序
/// </summary>
/// <typeparam name="T">排序的兑现</typeparam>
/// <param name="list">列表集合</param>
/// <param name="c">对比的对象</param>
public static void Sort<T>(this IList<T> list, Comparer<T> c)
{
if (list == null || list.Count == 0)
{
return;
}
for (int n = 0; n < list.Count - 1; n++)
{
for (int k = 0; k < list.Count - n - 1; k++)
{
if (c.Compare(list[k], list[k + 1]) > 0)
{
T tmp = list[k];
list[k] = list[k + 1];
list[k + 1] = tmp;
}
}
}
}
编写Compare类
public class PersonComparer : Comparer<Person>
{
public override int Compare(Person x, Person y)
{
if (x == null || y == null)
throw new ArgumentNullException();
return x.Name.CompareTo(y.Name);
}
}
使用:
ObservableCollection<Person> people = new ObservableCollection<Person>
{
new Person { Name = "Alice", IsWomen = true },
new Person { Name = "Bob", IsWomen = false },
new Person { Name = "Charlie", IsWomen = false },
new Person { Name = "Diana", IsWomen = true }
};
people.Sort(new PersonComparer());
foreach (var person in people)
{
Console.WriteLine($"{person.Name}, IsWomen: {person.IsWomen}");
}
若需要男性或女性先排前面,则加多一个判断:
public class PersonComparer : Comparer<Person>
{
public override int Compare(Person x, Person y)
{
if (x == null || y == null)
throw new ArgumentNullException();
// 首先比较 IsWomen 属性
if (x.IsWomen != y.IsWomen)
{
// 如果 x 是女性而 y 不是,或者 x 不是女性而 y 是,则 x 应该排在 y 前面(或反之,取决于您的排序需求)
// 这里我们假设您想让 IsWomen 为 true 的排在前面
return x.IsWomen.CompareTo(y.IsWomen);
}
// 如果 IsWomen 相同,则比较 Name 属性
return x.Name.CompareTo(y.Name);
}
}