Sunday, 10 June 2012

C# LINQ Grouping Search using "Key"

LINQ is quite useful because you can write SQL in C#. It may be confusing at first, thought.
Key is used with group clause. The following websites can be helpful.

http://msdn.microsoft.com/en-au/library/bb384063.aspx#Australia%20%28English%29
http://msdn.microsoft.com/en-us/library/vstudio/bb397927.aspx
--------------------------------------------------------------------------------------------------
namespace LINQ_programm
{
    class Program
    {
        static void Main(string[] args)
        {
            Method_1();
         }
           static void  Method_1()
        {
            Car[] cars = Planet.Cars;
            var group_query = from c in cars group c by c.Price into g select new { Price = g.Key, Cars = g };

            foreach (var g in group_query)
            {
                Console.WriteLine("\n---Car priced{0:c}", g.Price);
                foreach (var c in g.Cars)
                {
                    Console.WriteLine("\nMake:{0}\nModel:{1}\nYear:{2}\nPrice:{3:c}", c.Make, c.Model, c.Date_Made.Year, c.Price);
                }
            }
        }
}

No comments:

Post a Comment