C# 如何按特定属性分组并按其他属性排序?

C# 如何按特定属性分组并按其他属性排序?,c#,linq,select,group-by,sql-order-by,C#,Linq,Select,Group By,Sql Order By,我想做一个查询,得到postGroup和applicationserid的不同对,它们是Post表的属性。 我还想按其PostDate对所选帖子进行排序,这也是此表中的一个属性,我使用where条件仅选择我关注的用户或站点的帖子,或我的帖子 我无法做到这一点,但这是我所尝试的: var posts = (from m in context.Posts orderby m.PostDate descending

我想做一个查询,得到postGroup和applicationserid的不同对,它们是Post表的属性。 我还想按其PostDate对所选帖子进行排序,这也是此表中的一个属性,我使用where条件仅选择我关注的用户或站点的帖子,或我的帖子

我无法做到这一点,但这是我所尝试的:

 var posts = (from m in context.Posts
                     orderby m.PostDate descending
                     where ((context.FollowedUsers
        .FirstOrDefault(n => n.FollowerId == Id && n.ApplicationUserId == m.ApplicationUserId)) != null
        || (context.FollowedSites.FirstOrDefault(n => n.ApplicationUserId == Id && n.SiteId == m.SiteId) != null)
        || m.ApplicationUserId == Id)
                     group m by new { m.PostGroup, m.ApplicationUserId } into g
                     select new { g.Key.ApplicationUserId, g.Key.PostGroup } ).Skip(skip).Take(nOfPosts).ToList();
这将在不排序的情况下生成不同的对


感谢您的帮助

嗯。。我不确定你想要达到什么目标。您的查询看起来不错。你确定结果是错的吗? 按PostDate排序后,结果如下所示

Data        UserId      PostGroup
----------- ----------- -----------
3           10          1
2           20          2
2           10          2
1           20          2
按用户ID分组后,PostGroup结果应如下所示

UserId      PostGroup
----------- -----------
10          1
20          2
10          2
您的查询将生成该结果。 我重写了您的查询,您可以使用以下内容检查结果:

var posts = context.Posts.OrderByDescending(p => p.PostDate)
    .Where(m => context.FollowedUsers.FirstOrDefault(n => n.FollowerId == Id && n.ApplicationUserId == m.ApplicationUserId)) != null || (context.FollowedSites.FirstOrDefault(n => n.ApplicationUserId == Id && n.SiteId == m.SiteId) != null) || m.ApplicationUserId == Id)
    .GroupBy(group => new { group.PostGroup, group.ApplicationUserId })
    .Select(x => new { x.Key.ApplicationUserId, x.Key.PostGroup })
    .Skip(skip).Take(nOfPosts).ToList();

分组将删除排序。每个组都可以包含任何
PostDate
,并且不可能在该点上确定组的排序日期

您必须将排序移过分组:

var posts=(来自context.posts中的m
其中context.FollowedUsers.Any(n=>n.FollowerId==Id&&n.applicationserid==m.applicationserid)
||context.FollowedSites.Any(n=>n.applicationSerid==Id&&n.SiteId==m.SiteId)
||m.applicationserid==Id
群m由新的{m.PostGroup,m.applicationserid}变成g
orderby g.Max(m=>m.PostDate)递减
选择新的
{
g、 Key.applicationSerid,
g、 Key.PostGroup
}).Skip(Skip).Take(nOfPosts.ToList();

旁注:我还将一些谓词修改为
Any

,您可以发布一些示例数据和预期结果吗?谢谢!非常感谢。您好,此查询不保留顺序。谢谢。