Tuesday, 13 September 2011

Grouping and sorting throug Linq

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for Movie
/// </summary>
public class Movie
{
    public string Title { get; set; }
    public string Director { get; set; }
    public int Genre { get; set; }
    public int RunTime { get; set; }
    public DateTime ReleaseDate{get;set;}

    public Movie()
    {
        //
        // TODO: Add constructor logic here
        //
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for Movie1
/// </summary>
public class Movie1
{
    public int Genre { get; set; }
    public int MovieCount { get; set; }

   
    public Movie1()
    {
        //
        // TODO: Add constructor logic here
        //
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default3 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        var mo = GetMovies();
        Dictionary<int, Movie1> groups = new Dictionary<int, Movie1>();
        foreach (Movie m in mo)
        {

            if (!groups.ContainsKey(m.Genre))
            {
                groups[m.Genre] = new Movie1 { Genre = m.Genre, MovieCount = 0 };
            }
            groups[m.Genre].MovieCount++;

        }

        List<Movie1> results = new List<Movie1>(groups.Values);
        results.Sort(delegate(Movie1 x, Movie1 y)
        {
            return
                x.MovieCount > y.MovieCount ? -1 :
                x.MovieCount < y.MovieCount ? 1 : 0;
        });

        GridView1.DataSource = results;
        GridView1.DataBind();
    }
public List<Movie> GetMovies()
    {
    return new List<Movie> {new Movie {Title ="Ram", Director ="ABHI" ,Genre =0, ReleaseDate =DateTime.Parse ("05/12/2001"),RunTime =89},
        new Movie {Title ="Gopal",Director ="Rohit",Genre =1,ReleaseDate =DateTime .Parse ("4/12/2002"),RunTime =96},new Movie {Title ="Ram",Director ="AMIT", Genre =1,ReleaseDate =DateTime .Parse ("04/12/2011"),RunTime =34}
    };
   
    }
}

output-:
GenreMovieCount
12
01



No comments:

Post a Comment