linq 按元素索引排序列表有效方法

6tqwzwtp  于 2022-12-06  发布在  其他
关注(0)|答案(3)|浏览(101)

我有一个书单如下:

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" }
}

我能知道它简化后怎么写吗?

eanckbw9

eanckbw91#

您只想reverse该列表吗?然后用途:

books.Reverse();

或者您可以使用Reverse extension method,它不会修改原始集合:

var ordered = books.AsEnumerable().Reverse();

您也可以使用Select多载来取得索引:

books = books 
    .Select((book, index) => (book, index))
    .OrderByDescending(x => x.index)
    .Select(x => x.book)
    .ToList();
ff29svar

ff29svar2#

定义一个索引或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();
5kgi1eie

5kgi1eie3#

我通常也需要使用固定索引,我已经做了一个简单的通用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();

相关问题