【问题标题】:How to order a list of classes by a dictionary key within the class using OrderBy?如何使用 OrderBy 通过类中的字典键对类列表进行排序?
【发布时间】:2018-10-16 23:39:41
【问题描述】:

如何通过类中的字典键对类列表进行排序 比如……

List<City> cities;

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

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

例如 伦敦 巴黎 纽约

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

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

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

【问题讨论】:

  • 你是指那个字典中的特定值?
  • 嗯,那是一本字典。您希望如何通过包含多个键和值的完整字典进行排序?你应该告诉我们更多关于逻辑的信息。这就像说我想按居民对城市进行排序一样,如果没有其他信息,意义不大。在这种情况下,按人口对城市进行排序会很有用,因此在您的样本中,您可以使用 someClass.OrderBy(x =&gt; x.SomeProperty.Count)
  • 你想使用 lambda 先排序字典,然后使用投影将其投影到 someClass 中吗?
  • 按 SomeProperty 的项目数排序?通过它的哈希码?我们需要这方面的更多信息。
  • 您考虑过使用SortedDictionary吗?

标签: c# lambda


【解决方案1】:

你像这样使用 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/

【讨论】:

  • 这不是错误消息。尝试展开结果视图。
  • 我在实际代码中使用您的答案... model.VacancyList.OrderBy(model.VacancyList => model.VacancyList.CustomAttributes["这个角色需要公司的汽车吗?"] ); ...但是我得到语法错误','预期
  • 该消息意味着订购您的城市的查询尚未实际运行。它被称为延迟执行。只要有人(或某物)开始查看结果,它就会运行 - 例如通过扩展结果视图。如果您想在不必展开结果视图的情况下查看结果,请使用ities.OrderBy(city => city.CityAttributes["Currency"]).ToList();
  • 试试这个:model.VacancyList.OrderBy(v => v.CustomAttributes["这个角色需要公司的车吗?"]).ToList();
  • 好的,我使用了 ToList() 但仍然得到语法错误,',' 预期
【解决方案2】:

您可以通过以下方式对其进行排序,说 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; }
}

【讨论】:

  • 我也去看看
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-03
  • 1970-01-01
  • 2015-08-05
相关资源
最近更新 更多