简体   繁体   English

实体框架 - 按降序排序,然后对该结果执行 Distinct 返回错误的结果

[英]Entity framework - Order by descending and then perform Distinct on that result returns the wrong results

I currently have a class that looks like this我目前有一个看起来像这样的 class

class Student
{
    [Key]
    public int StudentLogId { get; set; }
    public string Guid { get; set; }
    public string info { get; set; }
}

Now what I would like to do is to sort the result by descending based on the Id (last ones on the top) and then from those results get the distinct values (in short the sort order is important).现在我想做的是根据Id(最后一个在顶部)对结果进行降序排序,然后从这些结果中得到不同的值(简而言之,排序顺序很重要)。 I noticed that if I do this我注意到如果我这样做

//Order the students in descending order based on their id //根据学生的id降序排列学生

List<string> lst = StudentLogHistoryModel.OrderByDescending(s => s.StudentLogId).Select(u => u.Guid).ToList<string>();

The above returns the correct result in the right order now I would like to only get the unique values so I tried adding to the above query and came up with this上面以正确的顺序返回正确的结果现在我只想获取唯一值所以我尝试添加到上面的查询并想出了这个

List<string> lst = StudentLogHistoryModel.OrderByDescending(s => s.StudentLogId).Select(s => s.Guid).Distinct().ToList<string>();

However I noticed that in the second one the order got messed up.但是我注意到在第二个中订单搞砸了。 Any suggestions on why the order does not get preserved?关于为什么订单没有得到保留的任何建议? How can I fix this?我怎样才能解决这个问题?

What I mean by order getting messed up was suppose the first result i got this [A,A,B,B,D] I was expecting to get [A,B,D] after the second query.我所说的订单搞砸的意思是假设我得到的第一个结果是[A,A,B,B,D]我希望在第二个查询之后得到[A,B,D] However I get something like [D,A,B]但是我得到类似 [D,A,B]

As per the docs :根据文档

The query behavior that occurs as a result of executing an expression tree that represents calling Distinct(IQueryable) depends on the implementation of the type of the source parameter.由于执行表示调用 Distinct(IQueryable) 的表达式树而发生的查询行为取决于源参数类型的实现。 The expected behavior is that it returns an unordered sequence of the unique items in source.预期的行为是它返回源中唯一项的无序序列。

The key bit there is 'unordered'.那里的关键位是“无序的”。 IQueryable's Distinct does not guarantee that order is maintained. IQueryable 的Distinct不保证保持顺序。 As such, you need to OrderBy after the Distinct .因此,您需要OrderByDistinct之后。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM