LinQ表达式的一点点总结(二)select中新建对象
先建一个实体类
class Customer
{
public String ID { get; set; }
public String Name { get; set; }
public String Country { get; set; }
public String Price { get; set; }
public override string ToString()
{
return "ID = "+ID+",Name = "+Name+",Country = "+Country+",Price = "+Price;
}
}
对这个实体类进行相应的查询
List<Customer> lists = new List<Customer>
{
new Customer
{ID ="0001",
Name = "computer",
Country = "korea",
Price = 111},
new Customer
{ID ="0002",
Name = "phone",
Country = "japan",
Price = 111},
new Customer
{ID ="0003",
Name = "pad",
Country = "usa",
Price = 111},
new Customer
{ID ="0004",
Name = "map3",
Country = "china",
Price = 111},
new Customer
{ID ="0005",
Name = "fuduji",
Country = "china",
Price = 111},
};
var item = from n in lists
where n.Country == "china"
select n;
foreach (Customer i in item)
{
Console.WriteLine(i);
}
var item = from n in lists
where n.Country == "china"
select n.Name;//改成select n.Name+"er"; 在查询出的数据后面加一个尾巴再输出
foreach (String i in item)
{
Console.WriteLine(i);
}
Console.ReadKey();
---------------------------------------------------------
后面的查询部分还可以改成这样
var item = from n in lists
where n.Country == "china"
select new { n.Name,n.Country };//在select语句中映射多个属性只能用这种创先新对象的方式
foreach (var i in item)
{
Console.WriteLine(i);
}
//另外还有一种相类似的方法,应该说这才是真正的在select语句里面创建新的方法,这种方法常用在先给要查询的实体类实例化,然后再从中查询需要的内容(干巴巴的我也讲不太清楚,看看代码)
先创建一个实体类是用来提供数据的
class Com
{
public String A { get; set; }
public String B { get; set; }
public String C { get; set; }
public String D { get; set; }
}
再创建一个实体类(就是上个例子用到的那个类)
class Customer
{
public String ID { get; set; }
public String Name { get; set; }
public String Country { get; set; }
public String Price { get; set; }
public override string ToString()
{
return "ID = "+ID+",Name = "+Name+",Country = "+Country+",Price = "+Price;
}
}
接下来是具体的使用了
List<Com> lists = new List<Com>
{
new Com
{
A = "111",
B = "222",
C = "333",
D = "444"
},
new Com
{
A = "aaa",
B = "bbb",
C = "ccc",
D = "ddd"
},
new Com
{
A = "AAA",
B = "BBB",
C = "CCC",
D = "DDD"
}
};
var item = from n in lists
select new Customer
{
ID = n.A,
Name = n.B,
Country = n.C,
Price = n.D
};
foreach(var i in item)
{
Console.WriteLine(i);
}
Console.ReadKey();
}
这种做法在解析数据会时常用到,有时间再回过头来看看