【问题标题】:Why LINQ Distinct() does not preserve order list? [duplicate]为什么 LINQ Distinct() 不保留订单列表? [复制]
【发布时间】:2019-01-10 00:04:49
【问题描述】:

我有两列 DatePersonInCharge,我想按日期降序对列表进行排序,然后返回唯一没有重复的人名的列表。我使用Distinct() 过滤最终名单,但我不知道为什么列表顺序总是按字母顺序而不是降序。

到目前为止,这是我的代码:

  IList<string> model.StaffNames = await _context.FarmDiary
    .Select(f => new { f.PersonInCharge, f.Date })
    .OrderByDescending(x => x.Date)
    .Select(x => x.PersonInCharge)
    .Distinct()
    .ToListAsync();  

【问题讨论】:

  • 如果这是解析为某些 SQL 命令的 Linq2Entities,它是纯自然的,因为顺序语句总是出现在任何不同或分组之后。无论如何,语句的顺序很大程度上取决于底层的 linq-provider。对于 Linq2Objects,应该保留顺序。
  • 在大多数 DBMS 中 distinct 是通过排序和与以前的比较来实现的,这意味着 distinct 可能会推翻您之前所做的任何排序。提供者的一种合理方法是在 .Distinct() 调用之前忽略所有排序(因为 .net .Distinct() 不保证保留顺序,或者它们甚至不会不一致)
  • 执行的查询被简化为SELECT DISTINCT PersonInCharge FROM FarmDiary。由于 distinct 可以使用索引来加快查询速度,因此结果的顺序将取决于可用的索引(原因参见其他 cmets)。

标签: c# entity-framework linq


【解决方案1】:

Distinct() 是关于返回不同的行,它不承诺任何顺序,但仍然对其操作进行排序。订购有 OrderBy、OrderByDescending。在您的情况下,由于您的最终列表中没有日期,因此您不能按日期排序。

编辑:

void Main()
{
    List<FarmDiary> farmDiary = new List<FarmDiary> {
        new FarmDiary{Id=1, PersonInCharge="Bob",Date=new DateTime(2018,6,1)},
        new FarmDiary{Id=2, PersonInCharge="John",Date=new DateTime(2018,6,2)},
        new FarmDiary{Id=3, PersonInCharge="Bob",Date=new DateTime(2018,6,15)},
        new FarmDiary{Id=4, PersonInCharge="David",Date=new DateTime(2018,7,1)},
        new FarmDiary{Id=5, PersonInCharge="Zachary",Date=new DateTime(2018,6,10)},
    };

    List<string> staffNames = farmDiary
    .GroupBy(d => d.PersonInCharge)
    .OrderByDescending(x => x.OrderByDescending(d => d.Date).First().Date)
    .Select(x => x.Key)
    .ToList();

    staffNames.Dump();
}

public class FarmDiary
{ 
    public int Id { get; set; }
    public string PersonInCharge { get; set; }
    public DateTime Date { get; set; }
}

【讨论】:

  • 那么在我的情况下有什么解决方案可以实现吗?
  • 选择后,您可以使用 .GroupBy(x=>x.PersonInCharge).Select(x=>x.FirstOrDefault()).OrderByDescending(x=>x.Date).Select( x=>x.PersonInCharge).ToListAsync(); (或类似的东西; GroupBy().FirstOrDefault() 是缺少 .DistinctBy() 方法的解决方法)
  • @HoàngNguyễn,我编辑了我的消息以显示一个解决方案,实际上在某种程度上基于 DevilSuichiro 的评论。
  • 是的,@DevilSuichiro 的解决方案工作正常,我不需要操作模型,但还是谢谢你。
  • @HoàngNguyễn,“我不需要操纵模型”是什么意思?解决方法如上。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-18
  • 2020-11-26
  • 1970-01-01
相关资源
最近更新 更多