简体   繁体   English

按数组元素排序 Linq 列表

[英]Ordering Linq list by array elements

I have below code -我有以下代码 -

var refNosToOrder = new int[9] {1,2,3,4,5,6,7,8,9}

var orderedList = lst.OrderBy(x=>x.RefNo==7)
                     .ThenBy(y=> refNosToOrder.Contains(y.RefNo)).ToList();

lst is list of class object containing int property - RefNo: ie List<SampleClass> lst是包含 int 属性的 class object 的列表 - RefNo: ie List<SampleClass>

class SampleClass
{
  public int RefNo {get;set;}
}

lst contains all the unsorted data of RefNo : lst包含RefNo的所有未排序数据:

lst = 2,4,6,9,7,5,8,1,3

What I want to do -我想做的事 -

First I want to order lst by keeping first element as - 7 ;首先,我想通过将第一个元素保留为 - 7来订购lst then for the rest of the list, it should be ordered as the array refNosToOrder那么对于列表的 rest,它应该被排序为数组refNosToOrder

ie Final output I am expecting to be -即最终 output 我期望是 -

7,1,2,3,4,5,6,8,9

With the above code -使用上面的代码 -

var orderedList = lst.OrderBy(x=>x.RefNo==7)
                         .ThenBy(y=> refNosToOrder.Contains(y.RefNo)).ToList();

It is giving - 2,4,6,9,7,5,8,1,3 ie this code is not at all ordering the list.它给出了 - 2,4,6,9,7,5,8,1,3 ,即这个代码根本没有对列表进行排序。

Contains returns a boolean of whether an element is in a list or not, which won't be very helpful here. Contains返回一个元素是否在列表中的 boolean,这在这里不会很有帮助。 Instead, you could sort by the index of that element:相反,您可以按该元素的索引进行排序:

var orderedList = 
    lst.OrderBy(x => x.RefNo != 7)
       .ThenBy(y => Array.IndexOf(refNosToOrder, y.RefNo))
       .ToList();

EDIT:编辑:
Following up on Jeroen Mostert's comment, this sorting has quadratic complexity.继 Jeroen Mostert 的评论之后,这种排序具有二次复杂性。 For large refNosToOrder it may be more efficient to first convert the array to a dictionary of orders and then use it for the sorting:对于较大refNosToOrder ,首先将数组转换为订单字典然后将其用于排序可能更有效:

var orderDict = 
    Enumerable.Range(0, refNosToOrder.Length).ToDictionary(i => refNosToOrder[i]);
var orderedList = 
    lst.OrderBy(x => x.RefNo != 7).ThenBy(y => orderDict[y.RefNo]).ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM