如何使用Linq按属性值排序列表

时间:2016-05-25 03:22:54

标签: c# linq lambda

我需要订购名为preferences的列表中定义的项目。

List<String> preferences = new List<String> { "first","second","third" };
IEnumerable<mylist> orderedData = mylist.OrderBy(item => preferences.IndexOf(item));

ordereddata 输出应为

first
second
third... //Remaining property values comes here

请提出建议。

2 个答案:

答案 0 :(得分:0)

如果首选列表中有可用的索引,请使用int.MaxValue将其保留在最后。

List<String> preferences = new List<String> { "first","second","third" };
IEnumerable<MyList> orderedData = mylist.OrderBy(item => 
                                         {
                                              var index = preferences.IndexOf(item);   // use property if item is an object.
                                              return index>=0 ? index: int.MaxValue;
                                         });

选中此example

答案 1 :(得分:0)

var entryID = $(this).attr('id');
var locations = <?php echo json_encode($locations); ?>; // i suppose this could be array.
var floor = locations[entryID]['floor']; // <----target the floor here

if (floor === 'firstFloor') {
  $("#drawTable").css("background", "('images/firstFloor.jpg') 50% 100% no-repeat;");
} else if (floor === 'secondFloor') {
  $("#drawTable").css("background", "url('images/secondFloor.jpg') 50% 100% no-repeat;");
}