zoukankan      html  css  js  c++  java
  • 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  
    };  
  • 相关阅读:
    为什么需要配置环境变量
    Highcharts使用简例 + 异步动态读取数据
    使用SQL检测死锁
    2015.12.21-2015.12.25单词
    SQL Server锁定【2015.12.17】
    SQL SERVER 并发【2015.12.16】
    SQL闲杂知识点汇总【2015年12月】
    键和约束【2015.12.11】
    [笔记]聚集索引和非聚集索引相关知识点
    论Top与ROW_NUMBER读取第一页的效率问题
  • 原文地址:https://www.cnblogs.com/zlero/p/4341476.html
Copyright © 2011-2022 走看看