linq 有人能给我解释一下下面的代码吗?

iezvtpos  于 2023-01-28  发布在  其他
关注(0)|答案(1)|浏览(136)

我在解释其他人的代码时遇到问题。
我知道你的行为,但我不明白你是怎么做的。行为:

  • driverRemark有序号,可以链接到一个组,包含序号最小的备注的组应该先打印出来,依此类推,如果有2个备注序号最小,则最小的组应该先打印出来,除非为空,否则最后打印空。

有人能给我解释一下这是怎么回事吗?

var groupedDriverRemarks = driverRemarks
                .GroupBy(dr => dr.RemarkGroup)
                .OrderBy(g => g.Key == null)
                .ThenBy(g => g.Key)
                .OrderBy(gr => gr.Min(dr => dr.SeqNr))
                .SelectMany(g => g.OrderBy(dr => dr.SeqNr))
                .ToList();

 return groupedDriverRemarks;

我不知道这个功能是如何操作的。它确实工作,但不知道为什么。
先谢了
我试着搜索所有不同的LINQ方法,并试图翻译它。但没有任何结果。

brtdzjyr

brtdzjyr1#

下面是代码的注解版本:

var groupedDriverRemarks = driverRemarks
                .GroupBy(dr => dr.RemarkGroup) // group driver remarks by RemarkGroup
                .OrderBy(g => g.Key == null) // order groups so null RemarkGroup is last
                .ThenBy(g => g.Key) // order non-null remark groups by RemarkGroup
                .OrderBy(gr => gr.Min(dr => dr.SeqNr))
                // re-order remark groups by minimum of SeqNr; 
                // since previous ordering is preserved, any duplicate minimum SeqNr will be ordered by RemarkGroup with null last still
                .SelectMany(
                    g => g.OrderBy(dr => dr.SeqNr) // sort contents of each group in SeqNr order
                ) // flatten SeqNr sorted groups into single stream
                .ToList(); // convert ordered driver remarks to a List<T>

使用多个排序并不是处理子排序的有效方法,ThenBy方法就是为此而设计的,所以只有一个排序可以正常工作。它仍然有两种,我不这么认为;t

var orderedDriverRemarks =
    driverRemarks
        .OrderBy(dr => dr.SeqNr) // order all driver remarks by SeqNr
        .GroupBy(dr => dr.RemarkGroup) // group driver remarks by RemarkGroup
        // since GroupBy is order preserving, the group contents are still ordered by SeqNr
        .OrderBy(gr => gr.First().SeqNr) // order groups by minimum SeqNr
        .ThenBy(g => g.Key == null) // then order any dup min SeqNr groups so the null RemarkGroup is last if it exists
        .ThenBy(g => g.Key) // then order groups with non-null RemarkGroup by RemarkGroup
        .SelectMany(g => g) // flatten groups into single stream
        .ToList(); // convert ordered driver remarks to a List<T>

相关问题