如何使用OrderBy通过类中的字典键对类列表进行排序?

时间:2018-10-16 14:50:14

标签: c# lambda

如何通过班级中的字典键对班级列表进行排序 例如...

List<City> cities;

Public Class City
{
    public Dictionary<string, string> CityAttributes;
}

在这种情况下,我想按字典cities中的特定字符串对CityAttributes列表进行排序。

例如 伦敦 巴黎 纽约

每个城市都有一个CityAttribute词典...

<"Population over 6 million", "Yes">
<"Radius more than 15 miles", "No">
<"Currency","Euro">

我想按货币订购城市。结果列表为: 纽约 巴黎 伦敦

2 个答案:

答案 0 :(得分:3)

您可以像这样使用Linq的Orderby:

cities.OrderBy(city => city.CityAttributes["Currency"]);

如果您不想使用lambda,但是更易读,则可以执行以下操作:

var orderedCities = from city in cities
                    orderby city.CityAttributes["Currency"]
                    select city;

编辑:开始阅读linq的一个好地方是https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/

答案 1 :(得分:0)

您可以按照以下方式对它进行排序,说出OrderBy以使用CityAttributes值进行排序

cityList.Select(k => k.CityAttributes.OrderBy(x => x.Value)).ToList();

您的情况,

public static void Main()
{       
    var cityAttrib1 = new Dictionary<string, string>()
    {
        { "1", "Capital City"},
        { "2", "High Population"},
        { "3", "Good Transportation"}
    };

    var cityAttrib2 = new Dictionary<string, string>()
    {
        { "1", "Not a Capital City"},
        { "2", "Low Population"},
        { "3", "Poor Transportation"}
    };

    var city1 = new City { CityAttributes = cityAttrib1 };
    var city2 = new City { CityAttributes = cityAttrib2 };

    var list = new List<City> { city1, city2 };

    var sortedList = list.Select(k => k.CityAttributes.OrderBy(x => x.Value)).ToList();

    //Print the sorted output
    foreach(var item in sortedList)
    {
        foreach(KeyValuePair<string, string> entry in item)
        {
                Console.WriteLine(entry.Value); 
        }
        Console.WriteLine(Environment.NewLine);
    }
}

public class City
{
    public Dictionary<string, string> CityAttributes { get; set; }
}