简体   繁体   English

OrderByDescending 在我的 LINQ 查询中不起作用

[英]OrderByDescending not working in my LINQ query

I have come across a problem with a query where I'm trying to sort the result by descending but it doesn't do it.我遇到了一个查询问题,我试图通过降序对结果进行排序,但它没有这样做。 I have gone through few posts on stackoverflow with similar issue but none of the solutions seemed to work.我在stackoverflow上浏览了几篇类似问题的帖子,但似乎没有一个解决方案有效。 I was wondering if someone could point out what is wrong with my code.我想知道是否有人可以指出我的代码有什么问题。 Heres part of the query relevant to a problem:以下是与问题相关的查询部分:

from followup in ctx.FollowUps
    .Where(f => f.DestEntityId == user.Id 
           && f.DestEntityType == (int)ContactEntityTypeEnum.User)
    .OrderByDescending(x => x.AddDate)
select new
{ 
    user = new { Firstname = user.Firstname },
    followup = new { followup.NextFollowUpDate }
});

I also tried adding .ToList() before .OrderByDescending() but that didn't solve the problem either.我也尝试在 .OrderByDescending() 之前添加 .ToList() 但这也没有解决问题。

Following up the comments from @SILENT & @D.Shih your Linq expression is looking a bit odd.跟进@SILENT 和@D.Shih 的评论,您的 Linq 表达看起来有点奇怪。

var followUps =  ctx.FollowUps
    .Where(f => f.DestEntityId == user.Id 
           && f.DestEntityType == (int)ContactEntityTypeEnum.User)
    .OrderByDescending(x => x.AddDate)
    .Select(x => new
    { 
        UserFirstname = user.Firstname,
        AddDate = x.AddDate,
        FollowupDate = x.NextFollowUpDate
    }).ToList();

This will order the results by AddDate, not NextFollowUpDate, so I've added AddDate to the output just to avoid confusion between the two, since I don't know how you'd have assessed that they weren't in order based on only seeing the NextFollowUpDate.这将按 AddDate 而不是 NextFollowUpDate 对结果进行排序,因此我将 AddDate 添加到输出中只是为了避免两者之间的混淆,因为我不知道您如何评估它们不是仅基于看到 NextFollowUpDate。 I don't recommend mixing the LinQL (from/where/select) with the Fluent methods.我不建议将 LinQL (from/where/select) 与 Fluent 方法混合使用。 (above) (以上)

There doesn't look to be a point in returning each individual property in a separate anonymous type, just flatten it into a single package since anonymous types are intended for short lives and immediate consumption.以单独的匿名类型返回每个单独的属性似乎没有意义,只需将其扁平化为一个包,因为匿名类型旨在用于短暂的生命和立即消耗。

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

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