我有一个帖子列表,我有一个意见列表,4个意见用户可以为每个帖子投票。
就像:
POST1
Vote (opinion A | 10 votes), vote (opinion B | 2 votes), vote (opinion C | 1 votes), vote (opinion D | 0 votes)
POST2
Vote (opinion A | 3 votes), vote (opinion B | 4 votes), vote (opinion C | 5 votes), vote (opinion D | 7 votes)
对于任何用户在其日记中发布的每个帖子,其他用户可以投票1个意见。
在我的控制器中,我有这条线来获取日记帖子:
var diaryPosts = (from d in db.DiaryPosts
join e in db.EstadosDeAlma
on d.EstadosDeAlmaID equals e.ID
join u in db.User
on d.UserID equals u.ID
orderby d.ID descending
select new DiaryPostsSet
{
PostID = d.ID,
EstadoDeAlmaID = e.ID,
EstadoDeAlma = e.Title,
Author = u.Nickname,
Thumbnail = u.Thumbnail,
AuthorComment = d.Content,
Time = d.UpdateTime }).Take(6).ToList();
我试着为每个DiaryPost,它的意见投票,这是我的问题。我喜欢这样:
List<ImpressionsSet> impressions = new List<ImpressionsSet>();
foreach (var item in diaryPosts)
{
impressions = (from i in db.Impressions
select new ImpressionsSet
{
ImpressionID = i.ID,
ImpressionTitle = i.Impression,
UrlSlug = i.UrlSlug,
DiaryPostID = item.PostID,
ImpressionNum = i.DiaryImpressions.Count(d => d.DiaryPostsID == item.PostID)
}).ToList();
}
但''impressions'var只获得最后一个循环。我不知道如何解决这个问题,因为我对C#4.0中的数组和列表只有一些经验。我不知道我是否可以像印象一样使用它[n],我尝试过它并不起作用。
我还需要一个示例代码,说明如何在Razor View中控制此循环的结果。 我现在有这个:
@foreach (var imp in ViewBag.ImpressionsList)
{
if (item.PostID == imp.DiaryPostID)
{
<td>
@{ string cbName = imp.UrlSlug; }
@{ string impression = imp.ImpressionTitle; }
@{ string value = imp.DiaryPostID + "|" + imp.ImpressionID + "|" + Session["id"].ToString(); }
<a class="voto" href="javascript:;" onclick="PostImpressions('@value')">@impression</a>
</td>
<td>
<a class="num" href="javascript:;" onclick="PostImpressions('@value')">@imp.ImpressionNum</a>
</td>
}
}
但是我不确定它是否真的有效,因为我的印象var中没有2个帖子的结果,它只是得到了最后的结果。
有人可以帮助我吗?
答案 0 :(得分:1)
而不是:
impressions = ...
做
impressions.AddRange( (from i in db.Impressions
select new ImpressionsSet
{
ImpressionID = i.ID,
ImpressionTitle = i.Impression,
UrlSlug = i.UrlSlug,
DiaryPostID = item.PostID,
ImpressionNum = i.DiaryImpressions.Count(d => d.DiaryPostsID == item.PostID)
}).ToList() );