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>集合了,至于里面的值怎么对应,自己注意类型和大小就可以了,同时也可以做筛选!看个人需要!
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 {}如下:
- var result =from cust in customers where cust.City == "London"
-
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
};
人各有命,上天注定,有人天生为王,有人落草为寇。脚下的路,如果不是你自己的选择,那么旅程的终点在哪,也没人知道。你会走到哪,会遇到谁,都不一定。