C#中的lamda实用的select用法

1,集合通过select转匿名对象

List<DemoClass> liset = new List<DemoClass>(); 
DemoClass a0 = new DemoClass() { Id = 1, Name = "asd " };
DemoClass a1 = new DemoClass() { Id = 2, Name = "asd " };
liset.Add(a0);
liset.Add(a1);

var ss = liset.Select((p) => new { newid = p.Id }); //new {} 这样的写法创建匿名对象

还可以做出判断或者转换

var ss = liset.Select((p) => new { newid = p.Id, newName = p.Id.ToString() });

//就像这样,想怎么玩都行

2,有些时候是把这个对象转成另外的对象,以前的搞法就是循环,创建对象,给对象值赋值,对象集合添加,写法的态繁琐了

我们可以这么整

List<DemoClass> liset = new List<DemoClass>(); 
DemoClass a0 = new DemoClass() { Id = 1, Name = "asd " };
DemoClass a1 = new DemoClass() { Id = 2, Name = "asd " };
liset.Add(a0);
liset.Add(a1);
List<pople> poples = liset.Select((p) => new pople { PID = p.Id, PName = p.Id.ToString() }).ToList();

//这样就把 List<DemoClass> 集合值转到 List<pople>集合了,至于里面的值怎么对应,自己注意类型和大小就可以了,同时也可以做筛选!看个人需要! ———————————————— 版权声明:本文为CSDN博主「还有远方和田野」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 原文链接:https://blog.csdn.net/weixin_42780928/java/article/details/91490348

3.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();  
        }

4、 select 出对象的属性字段 

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

多个属性要用new {}如下:
  1. var result =from cust in customers where cust.City == "London"
  2.  
                select new{cust.City,cust.FirstName};//new{}   匿名函数

5.重命名, 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);  
}

6.直接实例化对象  //跟2有点相似

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

7.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 };
原文地址:https://www.cnblogs.com/ZkbFighting/p/12857667.html