您可以使用 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> // Notice the Inheritance to ObservableCollection
{
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" });
// Add your other books here........
collection.SetCriteria("ABC");
// your new collection is now sorted and ready to use, no need to write any extra sorting code here
请记住,如果您需要在排序中添加更多条件,唯一需要这样做的地方是 SetCriteria 方法。希望这会有所帮助。