Skip to main content
 首页 » 编程设计

c#之使用 Linq 获取帖子的投票计数

2024年02月20日14Renyi-Fan

这是我的数据库架构:

create table Post 
( 
    PostId int primary key identity, 
    ImageUrl nvarchar(1024) not null, 
    [Description] nvarchar(256) not null, 
    UserId int foreign key references [User](UserId), 
    DateOfPost datetime not null, 
    Score int 
) 
 
create table Vote 
( 
    VoteId int primary key identity, 
    UserId int foreign key references [User](UserId), 
    PostId int foreign key references Post(PostId), 
    VoteDirection bit not null, 
    DateOfVote datetime not null 
) 

基本上,我想按 [VoteDirection == true] - [VoteDirection == false] 对帖子进行排序。所以有 20 人投“真”,5 人投“假”,用于排序的临时分数为 15。

是否还有一种方法可以使用 DateOfVote 参数来选择日期范围?

这是我尝试过的:

    // www.foo.com/top/today 
    public ActionResult Today() 
    { 
        var posts = postRepository.FindAllPosts().Where(x => x.DateOfPost == DateTime.Today) 
                                                 .OrderByDescending(x => x.Votes.Where(c => c.VoteDirection == true) - x.Votes.Where(c => c.VoteDirection == false)); 
        return View(posts); 
    } 

我收到错误:

Error 2 Operator '-' cannot be applied to operands of type 'System.Collections.Generic.IEnumerable' and 'System.Collections.Generic.IEnumerable'

这是可以理解的,它们都是集合而不是实际的整数。但它应该说明我正在尝试做什么。有什么建议吗?

请您参考如下方法:

只需使用Count:

.OrderByDescending(x =>  
    x.Votes.Count(c => c.VoteDirection) - x.Votes.Count(c => !c.VoteDirection));