簡體   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