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  
};  

 

posted @ 2015-03-16 12:04  金楽  阅读(17088)  评论(2编辑  收藏  举报