C#------LINQ查询(一)

1.查询一定范围数字

        static void QueryInt()
        {
            // Specify the data source.
            int[] scores = { 97, 92, 81, 60 };

            // Define the query expression.
            IEnumerable<int> scoreQuery =
                from score in scores
                where score > 90
                select score;

            // Execute the query.
            foreach (int i in scoreQuery)
            {
                Console.Write(i + " ");
            }

            // Output: 97 92
        }

2.查询包含指定字符的字符

        static void QueryString()
        {
            // Specify the data source.
            string[] scores = { "SU001", "SU003", "EFUN", "ECHO" };

            // Define the query expression.
            IEnumerable<string> scoreQuery =
                from score in scores
                where score.StartsWith("SU")
                select score;

            // Execute the query.
            foreach (string i in scoreQuery)
            {
                Console.Write(i + " ");
            }

            // Output: SU001  SU003
        }

3.查询指定条件对象

    public class StudentScore
    { 
        public string StudentName { get; set; }

        public int MathScore { get; set; }

        public int EnglishScore { get; set; }

        public int ChineseScore { get; set; }


    }
        static void Main(string[] args)
        {
            //QueryInt();
            //QueryString();

            List<StudentScore> students = new List<StudentScore> 
            { 
                new StudentScore(){StudentName="SU001",MathScore=95,EnglishScore = 100,ChineseScore = 99},
                new StudentScore(){StudentName="SU003",MathScore=100,EnglishScore=100,ChineseScore=88},
                new StudentScore(){StudentName="S0004",MathScore=80,EnglishScore=80,ChineseScore=90}
            };

            //查询所有SU学生
            IEnumerable<StudentScore> studentQuery = from student in students
                                                     where student.StudentName.StartsWith("SU")
                                                     select student;
            //打印学生
            foreach (StudentScore s in studentQuery)
            {
                Console.WriteLine(s.StudentName);
            }


        }

 

posted @ 2024-09-18 13:55  echo-efun  阅读(26)  评论(0)    收藏  举报