C# LINQ查詢 類

iamzxf發表於2015-05-05

可以進一步將C#中的linq查詢與類、list等結合起來,通過下面的例子來說明:

(1)與陣列結合

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

namespace linqDemo2
{
    class Student
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
    
    class Program
    {
        static void Main(string[] args)
        {

            Student[] students = new Student[]
            {
                new Student{Name="zhangsan", Age=23},
                new Student{Name="lisi", Age=13},
                new Student{Name="wangwu", Age=18},
            };

            var q = from t in students
                    where t.Name[0] == 'z'
                    select t;

            foreach (var v in q)
                Console.WriteLine("Name: {0}, Age:{1}",v.Name, v.Age);

            Console.ReadLine();
        }
    }
}


(2)與泛型集合結合

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

namespace linqDemo2
{
    class Student
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
    
    class Program
    {
        static void Main(string[] args)
        {

            List<Student> students = new List<Student>()
            {
                new Student{Name="zhangsan", Age=23},
                new Student{Name="lisi", Age=13},
                new Student{Name="wangwu", Age=18},
            };

            var q = from t in students
                    where t.Name[0] == 'z'
                    select t;

            foreach (var v in q)
                Console.WriteLine("Name: {0}, Age:{1}",v.Name, v.Age);

            Console.ReadLine();
        }
    }
}


相關文章