Friday, August 5, 2011

Linq Class Item select with parentId beginner

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    // нэг мөр өгөгдөл
    public class Item
    {
        public int Id { get; set; }
        public int ParentId { get; set; }
        public string Name { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            //Хиймэл өгөгдлийн сан гэж үүсгэе
            IEnumerable<Item> menus = new Item[] {
            new Item { Id = 1, ParentId = 0, Name = "Name 1" },
            new Item { Id = 2, ParentId = 1, Name = "Name 2" },
            new Item { Id = 3, ParentId = 1, Name = "Name 3" },
            new Item { Id = 4, ParentId = 0, Name = "Name 4" },
            new Item { Id = 5, ParentId = 4, Name = "Name 5" },
            new Item { Id = 6, ParentId = 7, Name = "Name 6" },
            new Item { Id = 7, ParentId = 4, Name = "Name 7" }};

            // бүгдийг жагсааж байна
            var q = from m in menus
                    orderby m.ParentId, m.Id ascending
                    select m;

            foreach (var r in q)
            {
                Console.WriteLine("parent:{0} , {1} : {2}", r.ParentId, r.Id, r.Name);
            }
            q.ToString();

            // бүлэглээд жагсааж байна
            var q2 = from m in menus
                     group m by m.ParentId into collection
                     select new { Remainder = collection.Key, Rows = collection };

            foreach (var g in q2)
            {
                Console.WriteLine("Group хийгдсэн талбарын утга ParentId:{0} доторх мөрүүд:", g.Remainder);
                foreach (var r in g.Rows)
                {
                    Console.WriteLine("parent:{0} , {1} : {2}", r.ParentId, r.Id, r.Name);
                }
            }
            q2.ToString();

            // parentName -ийг харуулах
            // магадгүй зарим мэдээлэл нь бие бие дээрээ давхарлан оршдог тул энэ шүүлт тус болно

            Console.Clear();

            var query = from m in menus
                        orderby m.ParentId ascending
                        select new
                        {
                            m.Id,
                            m.Name,
                            m.ParentId,
                            ParentName = (m.ParentId == 0 ? "" : (from mm in menus
                                         where mm.Id == m.ParentId
                                         select mm.Name).Single())
                        };
            foreach (var r in query)
            {
                Console.WriteLine("parent:{0}|{1} , {2}|{3}", r.ParentId, r.ParentName, r.Id, r.Name);
            }
            query.ToString();
        }
    }
}

No comments: