基于另一个列表对列表进行排序,然后使用LINQ对自身进行属性排序 [英] Sort a list based on another list followed by a property on itself with LINQ

查看:30
本文介绍了基于另一个列表对列表进行排序,然后使用LINQ对自身进行属性排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下字典表示目标城市ID的键/值对以及与该城市关联的过滤器数量:

The following dictionary represents the key/value pair of a destination city ID and the number of filters associated to that city:

Dictionary<int, int> totalCityFilters

这本字典是按过滤器的降序排列的,这就是我需要的方式.然后,我有一个未分类的航班清单:

This dictionary is sorted by descending number of filters and it's the way I need it to be. I then have an unsorted list of flights:

List<Flight> unsortedFlights

每个 Flight 对象都有一堆属性,其中与我的问题最相关的是 DestinationID FinalPrice .我需要创建一个新的航班清单,并根据以下两个前提对它们进行排序:

Each Flight object has a bunch of properties where the most relevant to my problem are DestinationID and FinalPrice. I need to create a new list of flights where they are sorted based on the following 2 premisses:

  1. 首先应基于 totalCityFilters 的顺序对列表进行排序,该字典上的键与属性 DestinationID 相匹配.排期列表可能包含多个具有相同 DestinationID (不是主键)的排期.
  2. 然后应通过 FinalPrice 属性对列表进行排序(升序).
  1. The list should first be sorted based on the order of totalCityFilters, the key on that dictionary matches the property DestinationID. The flights list might have multiple flights with the same DestinationID (this is not the primary key).
  2. The list should then be sorted (ascending) by the FinalPrice property.

但是,第二种类型不能摧毁第一种.我的意思是,如果 B,便宜的航班(A)一定不能位于更昂贵的航班(B)之上.DestinationID 首先出现在 totalCityFilters 上的 A.DestinationID 上.

However, the second sort must not destroy the first one. I mean, a cheaper flight (A) must not be on top of a more expensive flight (B) if B.DestinationID appears first than A.DestinationID on totalCityFilters.

推荐答案

如果我正确理解了您的话:

If i have understood you correctly:

var result = unsortedFlights
             .OrderByDescending(f => totalCityFilters[f.DestinationID])
             .ThenBy( f => f.FinalPrice)
             .ToList();

如果 totalCityFilters 的值是您要首先订购的数字.

If the value of totalCityFilters is the number you want to order by first.

这篇关于基于另一个列表对列表进行排序,然后使用LINQ对自身进行属性排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆