mvc中的Linq groupby和count操作
这是我的表现
MyCourse (MyCourseID, CourseNumber, CourseName, SemesterName, Year)
在,如果表包含以下数据
ENG1200 'Basic English' Spring 2011
ENG1200 'Basic English' Spring 2011
,我只是尝试按如下方式提取计数和 CourseNumber
ENG1200 'Basic English' Spring 2011 2
,然后将其插入到新的强类型类中,以便我可以在视图中使用它。 但是 linq 语句打印每个类,每个类的计数为 1。
ENG1200 'Basic English' Spring 2011 1
ENG1200 'Basic English' Spring 2011 1
任何帮助将不胜感激。
这是我正在使用的 linq 代码:
public IQueryable<VotedCourses> GetVoted_Courses()
{
var votedCourses = courseDB.MyCourses.GroupBy
(x => new
{
x.MyCourseID,
x.CourseNumber,
x.CourseName,
x.SemesterName,
x.Year
})
.Select(x =>
new VotedCourses
{
MyCourseID = x.Key.MyCourseID,
CourseNumber = x.Key.CourseNumber,
CourseName = x.Key.CourseName,
SemesterName = x.Key.SemesterName,
Year = x.Key.Year,
VoteCount = x.Count()
});
return votedCourses;
}
So here is my table
MyCourse (MyCourseID, CourseNumber, CourseName, SemesterName, Year)
Now if the table consists of the following data
ENG1200 'Basic English' Spring 2011
ENG1200 'Basic English' Spring 2011
I am simply trying to extract the count along with the CourseNumber as follows
ENG1200 'Basic English' Spring 2011 2
and then insert it into a new strongly typed class so I can use it in my View.
But the linq statement prints every class with a count of 1 on each.
ENG1200 'Basic English' Spring 2011 1
ENG1200 'Basic English' Spring 2011 1
Any help will be greatly appreciated.
Here is my linq code that I am using:
public IQueryable<VotedCourses> GetVoted_Courses()
{
var votedCourses = courseDB.MyCourses.GroupBy
(x => new
{
x.MyCourseID,
x.CourseNumber,
x.CourseName,
x.SemesterName,
x.Year
})
.Select(x =>
new VotedCourses
{
MyCourseID = x.Key.MyCourseID,
CourseNumber = x.Key.CourseNumber,
CourseName = x.Key.CourseName,
SemesterName = x.Key.SemesterName,
Year = x.Key.Year,
VoteCount = x.Count()
});
return votedCourses;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我注意到您在匿名类型中包含了
x.MyCourseID
。此列不存在于您的示例中,它看起来像一个身份。我的猜测是该列在两条记录之间是不同的。我会将其从类型中删除,然后重试。I notice you're including
x.MyCourseID
in your anonymous type. This column isn't present in your samples, and it looks like an identity. My guess is that this column is different between the two records. I'd remove it from the type and try again.