• 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  
    };  
  • 相关阅读:
    sql server 纵横表的转换
    url参数的编码解码Demo
    SqlServer 列的增加和删除
    asp.net下ajax.ajaxMethod使用方法(转)
    js中document.all 的用法
    cookie跨域,跨目录访问及单点登录。
    错误记录:html隐藏域的值存字符串时出错
    .NET下用C#实现邮箱激活功能
    js与C#服务端 json数据交互
    sqlserver数据可空插入报错
  • 原文地址:https://www.cnblogs.com/zlero/p/4341476.html
Copyright © 2020-2023  润新知