你可以使用OrderBy和ThenBy。
var searches = new ObservableCollection<Book>();
searches.Add(new Book()
{
Desc = "The description of book 1",
Title = "ABC Book Title"
});
searches.Add(new Book()
{
Desc = "Book Title Only",
Title = "There's an ABC in the description of book 2"
});
searches.Add(new Book()
{
Desc = "Book Title ABC",
Title = "ABC is in the beginning"
});
var ordered = new ObservableCollection<Book>(searches.OrderBy(book => book.Title).ThenBy(book => book.Desc.Contains("ABC")));
更新
我已经添加了一个排名系统,希望能帮助你找到你想要的东西。我使用的只是IndexOf来确定您的条件的位置,并将其存储在Book对象内的属性中。我建议您为您的书籍创建一个独立的集合(使用继承),这样您就可以根据自己的需要自定义它,而不必在对象本身之外编写太多的代码。
public class BookCollection : ObservableCollection<Book>
{
public void SetCriteria(string search)
{
if(string.IsNullOrEmpty(search))
return;
foreach (var book in this)
{
if(book.Title.Contains(search))
book.TitleRank = book.Title.IndexOf(search, StringComparison.InvariantCulture);
if(book.Desc.Contains(search))
book.DescRank = book.Desc.IndexOf(search, StringComparison.InvariantCulture);
}
var collection = new List<Book>(base.Items.OrderBy(book => book.Title)
.ThenBy(book => book.Desc)
.ThenBy(book => book.TitleRank)
.ThenBy(book => book.DescRank));
Items.Clear();
collection.ForEach(Add);
collection.Clear();
}
}
public class Book
{
public string Title { get; set; }
public string Desc { get; set; }
public int TitleRank { get; internal set; }
public int DescRank { get; internal set; }
}
现在要使用这个新的集合,你只需要像这样调用它。
var collection = new BookCollection();
collection.Add(new Book { Desc = "Book Title ABC", Title = "ABC is in the beginning" });
collection.SetCriteria("ABC");
请记住,如果您需要在排序中添加更多条件,唯一需要进行此操作的地方是SetCriteria方法。希望这可以帮助您。
IComparer
和Sort
/OrderBy
吗? - Christoph Fink