ASP NET MVC如何在属性上调用Count然后打印出排序列表?

| 说我上了一堂课:
public class Post
{
    public int PostId { get; set; }
    public string Topic { get; set; }
    public int UserId { get; set; }
    [StringLength(5000)]
    public string Body { get; set; }
    public DateTime DateCreated { get; set; }
    public string Name { get; set; }
    public int Votes { get; set; }
} 
对于每个帖子,用户可以输入一个主题。例如,如果主题是\“ Red \” \“ Green \” \“ Blue \”和\“ Yellow \”,我如何基于使用这些主题的次数创建一个列表? 输出示例:
Red   | 70
Blue  | 60
Green | 40
Yellow| 35
编辑:这怎么不起作用,给我一个错误,我无法隐式转换类型?
public List<string> GetPopularTopics(int count)
    {
        var posts = from p in db.Posts
                    group p by p.Topic into myGroup
                    select new
                    {
                        Topic = myGroup.Key,
                        Count = myGroup.Count()
                    };
        return posts.ToList();
    }
编辑2: 因此,我尝试了达斯汀的解决方案,但出现错误。这是我使用的:
public IEnumerable<IGrouping<string,int>> GetPosts()
    {
        var posts = from p in db.Posts
                    group p by p.Topic into topicCounts
                    select new
                    {
                        Topic = topicCounts.Key,
                        Count = topicCounts.Count()
                    };
        return posts.ToList();
    }
这给我在posts.ToList()下的错误: 无法将类型\'System.Collections.Generic.List \'隐式转换为\'System.Collections.Generic.IEnumerable> \'。存在显式转换(您是否缺少演员表?)
已邀请:
如果执行投影并以form方法返回它,则必须创建一个新类型!
public class MyCounts
{
    public string Topic { get; set; }
    public int Count { get; set; }
}


public List<MyCounts> GetPopularTopics(int count)
{
    var posts = from p in db.Posts
                group p by p.Topic into myGroup
                select new MyCounts
                {
                    Topic = myGroup.Key,
                    Count = myGroup.Count()
                };
    return posts.ToList();
}
要创建分组,请创建一个匿名类型,例如:
var posts = from p in context.Posts
            group p by p.Topic into topicCounts
            select new
            {
                Topic = topicCounts.Key,
                Count = topicCounts.Count()
            };
然后使用日期,让它遍历一下:
foreach(var p in posts)
{
    Response.Write(String.Format(\"{0} - {1}\", p.Topic, p.Count));
}
问题是您需要使用非匿名类型作为返回值。 该查询创建一个IEnumerable匿名类型。
var posts = from p in context.Posts
        group p by p.Topic into topicCounts
        select new
        {
            Topic = topicCounts.Key,
            Count = topicCounts.Count()
        };
这是创建匿名对象的“ 8”语句。 您需要做的是创建一个非匿名对象-一个可以在此方法内部和外部共享的对象。 像这样:
public IEnumerable<TopicAndCount> GetPosts()
{
    var posts = from p in context.Posts
        group p by p.Topic into topicCounts
        select new TopicAndCount
        {
            Topic = topicCounts.Key,
            Count = topicCounts.Count()
        };
 }
请注意“ 10”语句和封闭方法的返回值。 那将解决您的问题。

要回复问题请先登录注册