Browsing articles tagged with " linq"
Group By, Group, Take and Order By with LinQ in C#
At some point you’ll need to group and order your results using LINQ. It’s an easy task but a little bit hard to master since you have a few options. Lets imagine we have Voting Poll that people will vote on periods. The voting Poll has 3 tables TimePeriod, Items and the Cross Reference table TimePeriod_Items and we want to build a results grid using them. The best option for me is the following. Notice I’m also limiting the results using the Take method this way I only have 3 items per Group. Also notice that I’m not returning an Anonymous Type but rather an ItemResults Type.
Code
public List FindResults()
{
var query = from items in db.TimePeriod_Items
group items by items.TimePeriod into g
orderby g.Key.finish
select new ItemResults
{
TimePeriod = g.Key,
TimePeriod_Item = g.Key.TimePeriod_Items.OrderByDescending(item => item.votes).Take(3)
};
return query.ToList();
}
ItemResult Class
public class ItemResults
{
public TimePeriod TimePeriod { get; set; }
public IEnumerable TimePeriod_Item { get; set; }
}
Use in ASP.NET MVC
public ActionResult Results()
{
var items = appRepository.FindResults();
return View("Results", items);
}




