EL02
EL02

Reputation: 322

Order by repeated times LINQ ASP.NET MVC

I have this Report model:

public class Report
{
    [Key]
    public int Id { get; set; }
    public string ReporterId { get; set; }
    [ForeignKey("ReporterId")]
    public virtual ApplicationUser Reporter { get; set; }
    public int ProductId { get; set; }
    [ForeignKey("ProductId")]
    public virtual Product Product { get; set; }
    public ReportType ReportType { get; set; }
}

Now, I want to return a List<Report> ordered by the most repeated element based on ProductId to the least repeated element.

Is there any way on how to do this with linq?

Upvotes: 0

Views: 90

Answers (1)

Robabeh Ghasemi
Robabeh Ghasemi

Reputation: 480

Try this:

var newList = List.GroupBy(p=> p.ProductId )
              .OrderByDescending(x=> x.Count())
              .SelectMany(x=> x).ToList();

Upvotes: 1

Related Questions