通过在实体框架上使用linq c#进行分组 [英] group by using linq c# on entity framework

查看:86
本文介绍了通过在实体框架上使用linq c#进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要按名称分组并汇总名称的所有实例 这是我在控制器中的代码:

I need to group by Names and to sum all the instance of the name this is my code in the controller:

public class FansController : Controller
{
    private dbFan db = new dbFan();

    public ActionResult Index()
    {
        var group = from f in db.fans
                    group f by f.TimeInClub;

        return View(group);
    }
}

这是我在模型中的代码:

this is my code in the model:

public class Fans
{
    public int ID { get; set; }
    [Required]
    public string Name { get; set; }
    [DisplayName("Last Name")]
    [Required]
    public string LastName { get; set; }
    [Required]
    [DisplayName("Gender")]
    public string MaleFemale { get; set; }
    [Required]
    [DisplayName("BirthDay")]
    [DataType(DataType.Date)]
    public DateTime BDate { get; set; }
    [Required]
    [DisplayName("Years in Club")]
    public string TimeInClub { get; set; }
}

,我需要的输出是包含2列的db:名称和实例号

and the output that I need is db that contains 2 columns: Name and Number of instance

在视图中,我正在使用@model IEnumeruble

In the view I'm using @model IEnumeruble

谢谢:)

推荐答案

var result = from f in db.fans
             group 1 by f.Name into g
             select new { Name = g.Key, Amount = g.Count() };

现在@model当前应为:

  • IEnumerable<dynamic>. From: view with IEnumerable of object type in MVC: @model IEnumerable<dynamic>
  • or that you create a class containing the two properties.

这篇关于通过在实体框架上使用linq c#进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆