【问题标题】:List sort based on another list基于另一个列表的列表排序
【发布时间】:2011-03-29 01:25:08
【问题描述】:

我有两个通用列表对象,其中一个包含 id 和排序,另一个包含一堆 id,例如,第二个列表中的每个 id 都具有对第一个列表的 id 引用;

public class OptionType
{
    public int ID { get; set; }
    public int Ordering { get; set; }
}

public class Option
{
    public int ID { get; set; }
    public int Type_ID { get; set; }
}   

显然,我可以通过以下方式对 OptionTypes 列表进行简单排序

types_list.OrderBy(x => x.Ordering);

问题是,我如何才能通过使用与 types_list 的排序相关的对象上的“Type_ID”来排序“options_list”。就像类似的东西(显然这是无效的 - 但希望你能明白这一点!)

options_list.OrderBy(x => x.Type_ID == types_list.OrderBy(e => e.Ordering));

【问题讨论】:

  • 我不明白,你能给我们一个示例,看看在给定一些输入的情况下排序后的输出可能是什么样子吗?

标签: c# linq sorting


【解决方案1】:

您应该能够使用连接来产生所需的输出。使用查询语法的示例。

var orderedOptions = from option in options_list
                     join type in types_list
                     on option.Type_ID equals type.ID
                     orderby type.Ordering
                     select option;

【讨论】:

  • 我使用这个方法的时候出现The incoming request has too many parameters错误,怎么办?
  • 成功了。干杯。我正在寻找类似的东西。经常忘记这种类型的 linq 语法:-/
【解决方案2】:

List.FindIndex() 是您处理小型列表时的朋友:

var orderedB = listB.OrderBy(b => listA.FindIndex(a => a.id == b.id));

工作示例:https://dotnetfiddle.net/CpLeFU

正如@goodeye 在 cmets 中指出的那样,在更大的列表中,性能将是一场噩梦。在这种情况下使用accepted answer

【讨论】:

  • 这比连接简单得多。这假定 listA 已按所需顺序(type.Ordering)排序。也就是说,它使用 listA 在列表中的位置,而不是 listA 的属性。它还在执行多个 FindIndex,因此在大型列表中可能存在性能问题。
  • 你真的拯救了我的一天
【解决方案3】:

我喜欢 Lambda 语法,所以我想出了这个等价物。我可以看到查询语法对于连接来说是如何更简洁的。

var orderedOptions = options_list
    .Join(
        types_list,
        option => option.Type_ID,
        type => type.ID,
        (option, type) => new { Option = option, Type = type })
    .OrderBy(x => x.Type.Ordering)
    .Select(x => x.Option);



为了稍微减少(我不确定是什么),这将创建仅具有 Ordering 属性的新对象,而不是整个 Type 类。这里没有太大不同,但我有一个带有排序数据的大类,只需要排序属性。不知道这是否重要,但阅读起来更清晰。

var orderedOptions = options_list
    .Join(
        types_list,
        option => option.Type_ID,
        type => type.ID,
        (option, type) => new { Option = option, Ordering = type.Ordering })
    .OrderBy(x => x.Ordering)
    .Select(x => x.Option);

看起来查询语法允许您在初始查询中进行排序,而 lambda 要求在连接创建新对象后进行排序。不过,也许他们真的在做同样的事情:创建连接对象,然后进行排序然后选择。

【讨论】:

    猜你喜欢
    • 2016-09-28
    • 1970-01-01
    • 2022-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-27
    • 1970-01-01
    • 2012-06-01
    相关资源
    最近更新 更多