C \ # 6 판 - 12 에 정통 (LINQ to Object)

LINQ 의 작은 실 용적 인 데모, 배 움 이 끝 이 없 는 길에 매일 조금씩 발전 해 야 지식 이 많이 쌓 이 잖 아 요.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Fun LQIN to Object");
            QueryOverStrings();
            QueryOverInts();

            IEnumerable subset = GetSttringSubset();
            foreach (var item in subset)
            {
                Console.WriteLine(item);
            }

            foreach (var item in GetStringSubsetArray())
            {
                Console.WriteLine(item);
            }

            Console.WriteLine("***********LINQ over Generic collections***************");
            List myCars = new List()
            {
                new Car{  PetName="Henry",Color="Silver",Speed=100,Mack="BMW"},
                 new Car{  PetName="Daisy",Color="Tan",Speed=90,Mack="BMW"},
                  new Car{  PetName="Mary",Color="Black",Speed=55,Mack="VW"},
                   new Car{  PetName="Clunker",Color="Rust",Speed=5,Mack="Yugo"},
                    new Car{  PetName="Melvin",Color="White",Speed=43,Mack="Ford"},
            };

            GetFastCars(myCars);
            GetFastBMWs(myCars);
            LINQOverArrayList();
            OfTypeAsFilter();

            ProductInfo[] itemInSrock = new[] 
            {
                new ProductInfo{Name="Mac' s Coffee",Description="Coffee with TEETH",NumberInStock=24},
                 new ProductInfo{Name="Milk Maid Milk",Description="Milk cow's love",NumberInStock=100},
                  new ProductInfo{Name="Pure Silk Tofu",Description="Bland as Possible",NumberInStock=120},
                   new ProductInfo{Name="Cruchy Pops",Description="Cheezy,peppery goodness",NumberInStock=2},
                    new ProductInfo{Name="RipOff water",Description="From the tap to your wallet",NumberInStock=100},
                     new ProductInfo{Name="Classic Valpo pizza!",Description="Everyone loves pizza",NumberInStock=73},
            };
            SelectEverything(itemInSrock);
            ListProductNames(itemInSrock);
            GetOverstock(itemInSrock);
            GetNameasDescriptions(itemInSrock);
            Array obj = GetProjectedSubset(itemInSrock);
            foreach (var item in obj)
            {
                Console.WriteLine(item.ToString());
            }

            GetCountFromQuery();
            ReverseFromQuery(itemInSrock);
            DispalyConcatNoDups();
            AvggregateOps();
            QueryStringWithEnumberableAndLambdas();
            Console.ReadLine();
        }

        #region LINQ
        /// 
        ///  LINQ         
        /// 
        static void QueryOverStrings()
        {
            string[] currentVideoGames = { "Morrowind", "Uncharted 2", "Fallout 3", "Daxter", "System Shock 2" };
            IEnumerable subset = from g in currentVideoGames
                                         where g.Contains(" ")
                                         orderby g
                                         select g;

            foreach (var item in subset)
            {
                Console.WriteLine("Item:{0}", item);
            }
        }

        /// 
        /// LINQ         
        /// 
        static void QueryOverInts()
        {
            int[] number = { 10, 20, 30, 40, 1, 2, 3, 9 };
            IEnumerable subset = from i in number
                                      where i < 10
                                      select i;
            foreach (var item in subset)
            {
                Console.WriteLine("Item:{0}", item);
            }
        }

        /// 
        ///        ,   Int      
        /// 
        static void ImmediateExecution()
        {
            int[] number = { 10, 20, 30, 40, 1, 2, 3, 9 };
            //       int[]
            int[] subsetIntArray = (from i in number where i < 10 select i).ToArray();

            //       List
            List subsetAsListArray = (from i in number where i < 10 select i).ToList();
        }



        /// 
        ///   IEnumberable,  LINQ     
        /// 
        /// 
        static IEnumerable GetSttringSubset()
        {
            string[] colors = { "Light Red", "Green", "Yellow", "Dark Red", "Red", "Purple" };
            //  ,subset Ienumberable     
            IEnumerable theRedColor = from c in colors
                                              where c.Contains("Red")
                                              select c;
            return theRedColor;
        }

        /// 
        ///         LINQ  ,  toArray     
        /// 
        /// 
        static string[] GetStringSubsetArray()
        {
            string[] colors = { "Light Red", "Green", "Yellow", "Dark Red", "Red", "Purple" };
            var theRedColor = from i in colors
                              where i.Contains("Red")
                              select i;
            //        
            return theRedColor.ToArray();
        }

        /// 
        ///         ,  Speed    55  
        /// 
        /// 
        static void GetFastCars(List myCars)
        {
            var fastCars = from c in myCars where c.Speed > 55 select c;
            foreach (var item in fastCars)
            {
                Console.WriteLine("{0} is going too fast!", item.PetName);
            }
        }

        /// 
        ///   Speed    90    
        /// 
        /// 
        static void GetFastBMWs(List myCars)
        {
            var fastCars = from c in myCars where c.Speed > 90 && c.Mack == "BMW" select c;
            foreach (var item in fastCars)
            {
                Console.WriteLine("{0} is going too fast!", item.PetName);
            }
        }

        /// 
        ///  LINQ          
        /// 
        static void LINQOverArrayList()
        {
            Console.WriteLine("***********LINQ over ArrayList************");
            ArrayList myCars = new ArrayList()
            {
                new Car{  PetName="Henry",Color="Silver",Speed=100,Mack="BMW"},
                 new Car{  PetName="Daisy",Color="Tan",Speed=90,Mack="BMW"},
                  new Car{  PetName="Mary",Color="Black",Speed=55,Mack="VW"},
                   new Car{  PetName="Clunker",Color="Rust",Speed=5,Mack="Yugo"},
                    new Car{  PetName="Melvin",Color="White",Speed=43,Mack="Ford"},
            };
            // arrayList        IENumberable  
            var myCarsEnum = myCars.OfType();
            var fastCars = from c in myCarsEnum where c.Speed > 55 select c;
            foreach (var item in fastCars)
            {
                Console.WriteLine("{0} is going too fast!", item.PetName);
            }
        }

        /// 
        ///   OfType          OfType     Int  ,    Int  
        /// 
        static void OfTypeAsFilter()
        {
            ArrayList arr = new ArrayList();
            arr.AddRange(new object[] { 10, 400, 8, false, new Car(), "String data" });
            var myInts = arr.OfType();
            foreach (var item in myInts)
            {
                Console.WriteLine("Int Value:{0}", item);
            }
        }

        /// 
        ///        
        /// 
        /// 
        static void SelectEverything(ProductInfo[] products)
        {
            //       
            Console.WriteLine("All Product details");
            var allProducts = from p in products select p;
            foreach (var item in allProducts)
            {
                Console.WriteLine("Name:{0}", item);
            }
        }

        /// 
        ///   LINQ          
        /// 
        /// 
        static void ListProductNames(ProductInfo[] products)
        {
            //        
            Console.WriteLine("Only Product Name:");
            var allProducts = from p in products select p.Name;
            foreach (var item in allProducts)
            {
                Console.WriteLine("Name:{0}", item);
            }
        }


        /// 
        ///   LINQ       25  
        /// 
        /// 
        static void GetOverstock(ProductInfo[] products)
        {
            //        
            Console.WriteLine("the overstock item:");
            var overstock = from p in products where p.NumberInStock > 25 select p;
            foreach (var item in overstock)
            {
                Console.WriteLine(item.ToString());
            }
        }

        /// 
        ///        ,select new {       }
        /// 
        /// 
        static void GetNameasDescriptions(ProductInfo[] products)
        {
            Console.WriteLine("Name And Descriotions:");
            var nameDesc = from p in products select new { p.Name, p.Description };
            foreach (var item in nameDesc)
            {
                Console.WriteLine(item.ToString());
            }
        }

        /// 
        ///   ToArray()    ,        .NET System.Array       select new {p.Name,p.Description}
        /// 
        /// 
        /// 
        static Array GetProjectedSubset(ProductInfo[] products)
        {
            var nameDesc = from p in products select new { p.Name, p.Description };
            return nameDesc.ToArray();
        }

        /// 
        ///   IEnumberable    
        /// 
        static void GetCountFromQuery()
        {
            string[] currentVideoGames = { "Morrowind", "Uncharted 2", "Fallout 3", "Daxter", "System Shock 2" };
            int num = (from i in currentVideoGames where i.Length > 6 select i).Count();
            Console.WriteLine("{0}Items honor the LINQ query.", num);
        }

        /// 
        ///      
        /// 
        /// 
        static void ReverseFromQuery(ProductInfo[] products)
        {
            Console.WriteLine("Product in reverse");
            var allProducts = from p in products select p;
            foreach (var item in allProducts.Reverse())
            {
                Console.WriteLine(item.ToString());
            }
        }

        /// 
        ///         ,     ,      ascending   ,      descending   
        /// 
        /// 
        static void AlPhabetizeProductNames(ProductInfo[] products)
        {
            //            
            var allProducts = from p in products orderby p.Name select p;
            Console.WriteLine("orderby name");
            foreach (var item in allProducts.Reverse())
            {
                Console.WriteLine(item.ToString());
            }
        }

        /// 
        ///      
        /// 
        static void DispalyConcatNoDups()
        {
            List myCars = new List() { "Yugo", "Aztec", "BMW" };
            List yourCars = new List() { "BMW", "Saab", "Aztec" };
            var carConcat = (from c in myCars select c).Concat(from c1 in yourCars select c1);
            foreach (var item in carConcat.Distinct())
                Console.WriteLine(item);
        }
        /// 
        ///        (max、min、avg、sum)
        /// 
        static void AvggregateOps()
        {
            double[] temps = { 2.0, -21.3, 8, -4, 0, 8.2 };
            //       
            Console.WriteLine("MAX:{0}",(from c in temps select c).Max());
            Console.WriteLine("Min:{0}", (from c in temps select c).Min());
            Console.WriteLine("Average:{0}", (from c in temps select c).Average());
            Console.WriteLine("Sum:{0}", (from c in temps select c).Sum());
        }

        /// 
        ///   Enumbetable   array            
        /// 
        static void QueryStringWithEnumberableAndLambdas() 
        {
            string[] currentVideoGames = { "Morrowind", "Uncharted 2", "Fallout 3", "Daxter", "System Shock 2" };
            //  Enumbetable   array            
            var subset = currentVideoGames.Where(x => x.Contains(" ")).OrderBy(x => x).Select(x => x);
            foreach (var item in subset)
                Console.WriteLine("item:{0}",item);
        }
        #endregion
    }
    class Car
    {
        public string PetName { get; set; }
        public string Color { get; set; }
        public int Speed { get; set; }
        public string Mack { get; set; }
    }

    class ProductInfo
    {
        public string Name { get; set; }
        public string Description { get; set; }
        public int NumberInStock { get; set; }

        public override string ToString()
        {
            return string.Format("Name={0},Description={1},NumberInStock={2}", Name, Description, NumberInStock);
        }
    }
}

  

좋은 웹페이지 즐겨찾기