user7024226
user7024226

Reputation: 79

group by using linq c# on entity framework

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; }
}

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

In the view I'm using @model IEnumeruble

Thanks :)

Upvotes: 1

Views: 1648

Answers (2)

Gilad Green
Gilad Green

Reputation: 37281

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

Now the @model should currently be:

Upvotes: 1

RaZoDiuM
RaZoDiuM

Reputation: 223

see this

Selecting count in LINQ

And try something like:

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

Upvotes: 0

Related Questions