Browsing articles in ".NET"

C# Form Validation Class

May 19, 2009   //   by Michael D. Irizarry   //   .NET, Databases  //  Comments Off

A nice little form validation class. It provides validation for Phone, Email, URL and Zipcode but its real easy to extend.
Read more >>

Group By, Group, Take and Order By with LinQ in C#

May 13, 2009   //   by Michael D. Irizarry   //   .NET, Databases  //  Comments Off

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<ItemResults> 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> TimePeriod_Item { get; set; }
}

Use in ASP.NET MVC

public ActionResult Results()
{
    var items = appRepository.FindResults();
    return View("Results", items);
}