使用数组对列表<对象进行排序>
本文关键字:排序 对象 数组 列表 | 更新日期: 2023-09-27 18:34:18
我似乎无法解决这个问题。
我有以下几点:
private String[] PREFERED = new String[] { "37", "22", "18" };
private List<Stream> library;
public class Stream
{
public String ID { get; set; }
public String URL { get; set; }
public String Description { get; set; }
public String Type { get; set; }
}
我想使用 PREFERED
String 数组对名为 library
的List<Stream>
进行排序,以便我的结果将是具有以下顺序的library
:35
、22
、18
,...
library = library.OrderBy(o => Array.IndexOf(PREFERED, o.ID)).ToList();
但是我没有得到预期的结果...
杰伦
[{"ID":"44","URL":null,"Description":".webm (854x480)","Type":".webm"},
{"ID":"35","URL":null,"Description":".3gp (854x480)","Type":".3gp"},
{"ID":"43","URL":null,"Description":".webm (640x360)","Type":".webm"},
{"ID":"34","URL":null,"Description":".flv (640x360)","Type":".flv"},
{"ID":"18","URL":null,"Description":".mp4 (480x360)","Type":".mp4"},
{"ID":"5","URL":null,"Description":".flv (400x240)","Type":".flv"},
{"ID":"36","URL":null,"Description":".flv (400x240)","Type":".flv"},
{"ID":"17","URL":null,"Description":".3gp (176x144)","Type":".3gp"}]
我认为这甚至适用于PREFERED
不包含 library
ID 的情况。
var ranks =
PREFERED
.Select((x, n) => new { x, n })
.ToLookup(xn => xn.x, xn => xn.n);
library =
library
.OrderBy(l =>
ranks[l.ID]
.DefaultIfEmpty(int.MaxValue)
.First())
.ToList();
根据评论中的要求,这是解释。
行.Select((x, n) => new { x, n })
将值序列投影到值序列及其在序列中的索引中。
该行.ToLookup(xn => xn.x, xn => xn.n)
将序列更改为类似字典的结构,该结构从提供的任何键返回零个或多个值的列表,而不管该键是否在原始序列中。如果键不在原始序列中,则返回一个空的值序列。
表达式ranks[l.ID]
获取library
序列中的每个 id 并应用查找,返回一系列值。表达式.DefaultIfEmpty(int.MaxValue)
确保序列至少有一个值,表达式.First()
返回序列的第一个值。因此,这可确保对于library
源中的任何 id,您可以从PREFERED
序列中获取可能的匹配索引值,或者如果 id 不在PREFERED
序列中,则int.MaxValue
。
然后是按返回值排序并使用 .ToList()
重新创建列表的简单问题。
我尝试在 Linqpad 中使用以下代码,它对我有用:
void Main()
{
String[] PREFERED = new String[] { "37", "22", "18" };
List<Stream> library = new List<Stream> () ;
library.Add (new Stream () {ID ="22" }) ;
library.Add (new Stream () {ID ="37" }) ;
library.Add (new Stream () {ID ="18" }) ;
library.Dump () ;
library.OrderBy(o => Array.IndexOf(PREFERED, o.ID)).ToList().Dump () ;
}
public class Stream
{
public String ID { get; set; }
public String URL { get; set; }
public String Description { get; set; }
public String Type { get; set; }
}
看起来您只是希望它们根据ID
字段按降序排列,为什么不这样做
library = library.OrderByDescending(x => Int32.Parse(x.ID)).ToList();