Linq 之 Select 和 where 的用法


最近開始學習linq.自己也總結一下,方便以后查閱。

 Select 同 Sql 中的 select 類似,即輸出我們要的東東,感覺在 linq 中更加強大。

Linq 可以對集合如數組、泛型等操作,這里我們對泛型類型進行舉例。建一個類如下:

public class Customer  
    {  
        public Customer(string firstName, string lastName, string city)  
        {  
            FirstName = firstName;  
            LastName = lastName;  
            City = city;  
        }  
public Customer()  
        {}  
        public string FirstName { get; set; }  
        public string LastName { get; set; }  
        public string City { get; set; }  
}  

1、 select 出對象,cust 是一個Customer 對象。

static void Main(string[] args)  
        {  
            List<Customer> customers = new List<Customer>()   
            {   
                new Customer("Jack", "Chen", "London"),  
                new Customer("Sunny","Peng", "Shenzhen"),  
                new Customer("Tom","Cat","London")  
            };  
            //使用IEnumerable<T>作為變量  
            var result =from cust in customers  
                        where cust.City == "London"  
                        select cust;  
            foreach (var item in result)  
            {  
                Console.WriteLine(item.FirstName+":"+item.City);  
            }  
            Console.Read();  
        }  

2、 select 出對象的屬性字段

var result =from cust in customerswhere cust.City == "London"  
         select cust.City  

多個屬性要用new {}如下:

var result =from cust in customers where cust.City == "London"  
                        select new{cust.City,cust.FirstName};  

3、  重命名, city 和 name 是隨便起的

var result =from cust in customers where cust.City == "London"  
                        select new{ city=cust.City, name ="姓名"+ cust.FirstName+""+cust.LastName };  
            foreach (var item in result)  
            {  
                Console.WriteLine(item.name+":"+item.city);  
            }  

4、 直接實例化對象

var result =from cust in customers where cust.City == "London"  
        select new Customer{ City = cust.City, FirstName = cust.FirstName }; 

5、 selec 中嵌套select

var result =from cust in customers  where cust.City == "London"  
            select new{ city = cust.City,   
name=from cust1 in customers where cust1.City == "London" select cust1.LastName  
};  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM