【问题标题】:Order IEnumerable<T> object based on Dictionary根据 Dictionary 对 IEnumerable<T> 对象进行排序
【发布时间】:2015-06-22 16:03:13
【问题描述】:

我有一个IEnumerable&lt;T&gt; 列表。 - T 是一个自定义类型,该类型的成员之一是一个名为 Id 的 int。

我还有一个Dictionary&lt;int, int&gt;object,第一个 int 是一个 Id(这个 id 将在 IEnumerable&lt;T&gt; 列表中。第二个 Int 是一个评级编号。

我想根据Dictionary&lt;int, int&gt; 内部的评级订购IEnumerable&lt;T&gt; 列表 - 最高优先

我可以通过 if 语句和循环来做到这一点,但我觉得这可以使用 linq/lambda 语句来完成。

有人知道如何做到这一点吗?

我猜像list.OrderBy(x =&gt; x.id == Dictionaryname. something something something

【问题讨论】:

  • 如果您想知道如何从字典中获取键的值,请查看Dictionary 的文档,其中有很多示例说明如何做到这一点。
  • 您可以在 OrderBy 方法上使用自定义比较器,该方法键入字典并检查项目 a 是否应该出现在项目 b 之前、相同位置或之后,或者您的字典由 id 属性键入,您可以直接在OrderBylamba 中访问字典

标签: c# .net linq generics dictionary


【解决方案1】:

只需使用OrderByDescending

var sorted = list.OrderByDescending(x => dictionary[x.id])

【讨论】:

  • 我现在要试试这个......但你能不能更好地解释一下它是如何根据字典中的评级数字(第二个 Int)来订购它的?我问这个是因为字典中的第一个int是id,我想按评分排序
【解决方案2】:

你可以这样做:

list.OrderByDescending(x => dictionary[x.id])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-18
    • 2010-11-16
    • 2013-11-25
    • 1970-01-01
    • 1970-01-01
    • 2019-07-02
    • 1970-01-01
    相关资源
    最近更新 更多