繁体   English   中英

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

[英]How to order a list of classes by a dictionary key within the class using OrderBy?

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

List<City> cities;

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

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

例如,伦敦,巴黎,纽约

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

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

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

您可以这样使用Linq的Orderby:

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

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

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

编辑: https: //docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/concepts/linq/是开始阅读linq的好地方。

你可以对它进行排序以下方式说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; }
}

暂无
暂无

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

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