Performing group ... by ... into query - CSharp LINQ

CSharp examples for LINQ:Group By

Description

Performing group ... by ... into query

Demo Code


using System;// w w w  .j a v  a 2 s .  c  o  m
using System.Collections.Generic;
using System.Linq;
using System.Text;

class MainClass
    {
        static void Main(string[] args)
        {
            IList<Item> datasource = createData();

            Console.WriteLine("group...by... query");
  

            Console.WriteLine("\n\ngroup...by...into query");
            // use the group into keywords
            var result2 = from e in datasource
                         group e by e.Color into g
                         select new
                         {
                            Color = g.Key,
                            Items = g
                         };

            foreach (var element in result2)
            {
                Console.WriteLine("\nElement for color {0}", element.Color);
                foreach (var fruit in element.Items)
                {
                    Console.WriteLine("Name: {0} Color: {1} Shelf Level: {2} days.",
                        fruit.Name, fruit.Color, fruit.Level);
                }
            }

        }

        static IList<Item> createData()
        {
            return new List<Item>()
            {
                new Item("Oracle", "green", 7),
                new Item("MySQL", "MySQL", 10),
                new Item("C", "green", 4),
                new Item("fig", "brown", 12),
                new Item("XML", "red", 2),
                new Item("file", "yellow", 10),
                new Item("PLSQL", "red", 7)
            };
        }
    }
    class Item
    {
        public Item(string namearg, string colorarg, int lifearg)
        {
            Name = namearg;
            Color = colorarg;
            Level = lifearg;
        }
        public string Name { get; set; }
        public string Color { get; set; }
        public int Level { get; set; }
    }

Result


Related Tutorials