linq頭脳嵐001_集約関数

7216 ワード

最大値Max()最小値Min()平均値Average()の合計個数Count()とSum()を求める
1、ソリッドBean
    public class Tuzi

    {

        public int Id { get; set; }

        public int Age { get; set; }

        public string Name { get; set; }

    }

2、実体初期化器
  static List<Tuzi> InitTuziInfo()

        {

            List<Tuzi> tuziList = new List<Tuzi> { 

             new Tuzi{ Name="Tuzi001", Age=10  },

             new Tuzi{ Name="Tuzi002", Age=24 },

             new Tuzi{ Name="Tuzi003", Age=33  },

             new Tuzi{ Name="Tuzi004", Age=47  },

             new Tuzi{ Name="Tuzi005", Age=59 },

             new Tuzi{ Name="Tuzi006", Age=65  },

             new Tuzi{ Name="Tuzi007", Age=76  },

             new Tuzi{ Name="Tuzi008", Age=80  } 

             };

            return tuziList;

        }

3、結果
 
 static void Main(string[] args)

        {

            List<Tuzi> tuziList = InitTuziInfo();

            #region 001  

            int maxAge = (from s in tuziList

                          select s).Max(a => a.Age);

            Console.WriteLine(" :" + maxAge);

            //Lambda  

            int minAge = tuziList.Select(a => a.Age).Min();

            //==> 

            //minAge = tuziList.Select<Tuzi, int>(delegate(Tuzi t)

            //{

            //    return t.Age;

            //}).Min();

            Console.WriteLine(" :" + minAge);



            int avgAge = (int)tuziList.Select(a => a.Age).Average();

            Console.WriteLine(" :" + avgAge);

            avgAge = (int)tuziList.Where(a => a.Age != maxAge && a.Age != minAge).Average(a => a.Age);

            Console.WriteLine(" , :" + avgAge);

            int ageCount = (int)tuziList.Select(a => a.Age).Count();

            Console.WriteLine(" :" + ageCount);



            int ageSum = (int)tuziList.Select(a => a.Age).Sum();

            Console.WriteLine(" :" + ageSum);

            #endregion 

   

            Console.ReadKey();

        }