Wednesday 9 May 2012

Group By in Linq

// Group by With Linq
   List<string> ls = new List<string>();

   using (LinqModel.LinqEntities ST1 = new LinqModel.LinqEntities())
   {
       var V = (from State in ST1.State_Master
                    group State by State.CountryID into temp
                    select new
                         {
                             T1 = temp.Key.Value,
                             T2 = temp
                         }).ToList();
               
                foreach (var c in V)
                {
                    for (int i = 0; i < c.T2.ToList().Count; i++)
                    {
                        ls.Add(c.T2.ToList()[i].StateName);
                    }
                }

   };

   // Group by With Linq using Lambada expression
   // Same Result as above
  
   using (LinqModel.LinqEntities ST1 = new LinqModel.LinqEntities())
   {
    var vLambada = ST.State_Master.GroupBy(state => state.CountryID).ToList();
  
          foreach (var state in vLambada)
            {
                for (int i = 0; i < state.Count(); i++)
                {
                    ls.Add(state.ToList()[i].StateName);
                }
            }
    };
            Rpt.DataSource = ls;
            Rpt.DataBind();

No comments:

Post a Comment