简体   繁体   中英

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

How does one order a list of classes by a dictionary key within the class eg...

List<City> cities;

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

In this scenario, I want to order the cities list by a particular string in the dictionary CityAttributes .

eg London Paris New York

Each city has a CityAttribute dictionary...

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

I want to order the cities by Currency. The resulting list would be: New York Paris London

You use Linq's Orderby like this:

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

If you don't want to use a lambda, but something more readable, you can also do this:

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

Edit: A good place to get started reading up on linq is https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/ .

You can sort it the below way saying OrderBy to order with the CityAttributes value

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

Your case,

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; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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