我有以下書籍清單:
List<book> books = new List<book>()
{
new() { bookName = "wingbook" },
new() { bookName = "Peter Pan" },
new() { bookName = "Apple Pie" },
new() { bookName = "Zebra" }
}
我想找到按索引降序(不是書名)按書籍排序的方法。預期結果是
result = {
{ bookName = "Zebra" },
{ bookName = "Apple Pie" },
{ bookName = "Peter Pan" },
{ bookName = "wingbook" }
}
我能知道怎么寫嗎?
uj5u.com熱心網友回復:
您只是想反轉串列?然后使用:
books.Reverse();
或者您可以使用不會修改原始集合的Reverse擴展方法:
var ordered = books.AsEnumerable().Reverse();
您還可以使用Select多載來獲取索引:
books = books
.Select((book, index) => (book, index))
.OrderByDescending(x => x.index)
.Select(x => x.book)
.ToList();
uj5u.com熱心網友回復:
為書籍定義一個索引或 id 欄位以進行訂購:
List<book> books = new List<book>()
{
new() { index = 0, bookName = "wingbook" },
new() { index = 1, bookName = "Peter Pan" },
new() { index = 2, bookName = "Apple Pie" },
new() { index = 3, bookName = "Zebra" }
}
var result = books.OrderByDescending(x => x.index).ToList();
uj5u.com熱心網友回復:
我通常還需要使用修復索引,并且我使用Class 轉換器擴展制作了一個簡單的泛型,以便它可以轉換任何List<>.
這是索引集合專案類,它包含索引、專案,并且還告訴它是第一個還是最后一個索引,無論排序如何。
public class IndexedCollection<T>
{
public int Index { get; private set; }
public T Value { get; private set; }
private int Count { get; set; }
public bool IsFirst { get { return Index == 0; } }
public bool IsLast { get { return Index == Count - 1; } }
public IndexedCollection(T value, int index, int count)
{
Value = value;
Index = index;
Count = count;
}
}
一個簡單的轉換擴展如下所示:
public static List<IndexedCollection<T>> WithIndex<T>(this List<T> list)
{
var count = list.Count;
return list.Select((value, index) => new IndexedCollection<T>(value, index, count)).ToList();
}
根據您的示例資料,使用它的典型方法如下:
List<book> books = new List<book>()
{
new() { bookName = "wingbook" }, // 0 (index it will be given when converted)
new() { bookName = "Peter Pan" }, // 1
new() { bookName = "Apple Pie" }, // 2
new() { bookName = "Zebra" } // 3
}
// convert to List<IndexCollection<Book>>()
// which doesn't required to alter the original object
var indexedBooks = books.WithIndex();
// want to sort by name
indexedBooks = indexedBooks.OrderBy(o => o.Value.bookName).ToList();
// sort again by index desc
indexedBooks = indexedBooks.OrderByDescending(o => o.Index).ToList();
// want to just return the book objects
var justTheBooks = indexedBooks.Select(o => o.Value).ToList();
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/510632.html
標籤:C#林克
