c# linq 使用

linq 的常用的操作。

1.準備數據

1.1 學生類

View Code
  public class Student
    {
        public int id
        {
            get;
            set;
        }

        public string Name
        {
            get;
            set;
        }

        public static List<Student> IniStudents(int count)
        {
            List<Student> students = new List<Student>();

            #region 初始化學生
            for (int i = 0; i < count; i++)
            {
                students.Add(new Student { id = i, Name = "gsw" + i.ToString() });
            }
            #endregion
            return students;
        }
    }

1.2 成績類

View Code
  public class Score:IComparable<Score>
    {
        public int Studentid
        {
            get;
            set;
        }

        public string Course
        {
            get;
            set;
        }

        public double Fraction
        {
            get;
            set;
        }

        public static List<Score> IniScore(List<Student> students)
        {
            List<Score> scores = new List<Score>();
            Random r = new Random((int)DateTime.Now.Ticks);
            foreach (var item in students)
            {
                Score score = new Score();
 
                score.Studentid = item.id;
                score.Fraction =r.Next(1,100)+ Math.Round(r.NextDouble(), 2);
                score.Course = "中文";
                scores.Add(score);
                score = new Score();
                score.Studentid = item.id;
                score.Fraction = r.Next(1,100) + Math.Round(r.NextDouble(), 2);
                score.Course = "英語";
                scores.Add(score);
                score = new Score();
                score.Studentid = item.id;
                score.Fraction = r.Next(1,100) + Math.Round(r.NextDouble(), 2);
                score.Course = "數學";
                scores.Add(score);

            }
            return scores;
        }



        #region IComparable<Score> 成員

        public int CompareTo(Score other)
        {
          return   this.Fraction.CompareTo(other.Fraction);
        }

        #endregion
    }

2.代碼調用。代碼裏面都有註釋,不需要解釋,代碼如下:

View Code
  class Program
    {

        static void Main(string[] args)
        {
            List<Student> students = Student.IniStudents(5);

            #region 初始化學生
            for (int i = 0; i < students.Count; i++)
            {
                Console.WriteLine(string.Format("序號:{0} 姓名:{1}", i, "gw" + i.ToString()));
            }
            #endregion

            List<Score> scores = Score.IniScore(students);

            Console.WriteLine("----------課程成績大於50的人");

            #region ----------課程成績大於50的人
            var sd = from n in scores
                     join m in students on n.Studentid equals m.id
                     where n.Fraction > 50 
                     select new { n, m.Name };
            foreach (var item in sd)
            {
                Console.WriteLine(string.Format("姓名:{0} 課程:{1}  分數:{2}",item.Name,item.n.Course,item.n.Fraction));
            }
            #endregion

            Console.WriteLine("----------數學大於50的人的課程和數量");
            #region ----------數學大於50的人的課程和數量
            var sd1 = from n in scores
                      where n.Fraction>50
                      group n by n.Course into p
                      select p;
            foreach (var item in sd1)
            {
                Console.WriteLine(string.Format("課程:{0} 數量:{1}", item.Key, item.Count()));

                foreach (var item1 in item)
                {
                    Console.WriteLine(string.Format("  學號:{0} 分數:{1}", item1.Studentid, item1.Fraction));
                }
            }
            #endregion

            Console.WriteLine("----------學生個們課程的成績");
            #region ----------學生個們課程的成績
            var sd2 = from m in students
                      join n in scores on m.id equals n.Studentid
                      join p in scores on m.id equals p.Studentid
                      where n.Course == "數學" || p.Course=="中文"
                      select new { m,math=n.Fraction,china=p.Fraction};

            foreach (var item in sd2)
            {
                Console.WriteLine(string.Format("姓名:{0}  數學:{1}  中文:{2}", item.m.Name, item.math,item.china));
            }
            #endregion

            Console.WriteLine("----------查找學生課程的成績");
            #region ----------查找學生課程的成績
            var sd3 = from m in students
                      join n in scores on m.id equals n.Studentid
                      where m.Name=="gsw2"
                      select new { m,n};
            Console.Write(string.Format("姓名:{0} ", sd3.FirstOrDefault().m.Name));
            foreach (var item in sd3)
            {
                Console.Write(string.Format("課程:{0} 分數:{1} ", item.n.Course, item.n.Fraction));
            }
            #endregion

            Console.WriteLine("----------找出各個課程的最好的成績和平均數值");
            #region ----------找出各個課程的最好的成績和平均數值
            var sd4 = from m in scores
                      group m by m.Course into p
                      select new
                      {
                          p.Key,
                          max = p.Max(),
                          Average = (from n in scores
                                                           where n.Course==p.Key
                                                           select n.Fraction).Average()};
            foreach (var item in sd4)
            {
                Console.WriteLine(string.Format("課程:{0} 成績{1} {2}", item.Key, item.max.Fraction, item.Average));
            }
            #endregion

            Console.WriteLine("----------in 語句查詢");
            #region ----------in 語句查詢
            int[] arr1 = { 1,2};
            var sd5 = from m in students
                      where arr1.Contains(m.id)
                      select m;
            foreach (var item in sd5)
            {
                 Console.WriteLine("學號:{0} 姓名:{1} ",item.id,item.Name);
            }
           
            #endregion

            Console.WriteLine("----------like 語句查詢");
            #region ----------like 語句查詢
            string strLike = "gsw";
            var sd6 = from m in students
                      where m.Name.Contains(strLike)
                      select m;
            foreach (var item in sd6)
            {
                Console.WriteLine("學號:{0} 姓名:{1} ", item.id, item.Name);
            }

            #endregion

            Console.WriteLine("----------let 語句查詢");
            #region ----------let 語句查詢
            var sd7 = from m in scores
                      let result=m.Fraction>80?"成績好":"成績差"
                      select new { m,result};
            foreach (var item in sd7)
            {
                Console.WriteLine("成績:{0} 結論:{1} ", item.m.Fraction, item.result);
            }

            #endregion

            Console.WriteLine("----------函數使用");
            #region ----------let 語句查詢
            strLike = "gsw3";
            var sd8 = from m in students
                      where IsExit(m.Name,strLike )
                      select m;
            foreach (var item in sd8)
            {
                Console.WriteLine("學號:{0} 姓名:{1} ",item.id, item.Name);
            }

            #endregion

            Console.ReadLine();
        }

        private static bool IsExit(string p, string strLike)
        {
           return p==strLike;
        }

    }
posted @ 2012-05-07 20:23  無限遐想  阅读(950)  评论(1编辑  收藏  举报