关于select、where 基础
刚开始看linq
问题:下面2句,分别用where,select ,有什么区别,查询结果是不是都一样
orders是List<Order>
var ordByCountry = orders.Where(order => order.ShipCountry.Equals(country));
var ordByCountry = orders.Select(order => order.ShipCountry.Equals(country));
public class Order
{
private int orderID;
private string customerID;
private decimal freight;
private string shipName;
private string shipAddress;
private string shipCity;
private string shipCountry;
public int OrderID { get; set; }
public string CustomerID { get; set; }
public decimal Freight { get; set; }
public string ShipName { get; set; }
public string ShipAddress { get; set; }
public string ShipCity { get; set; }
public string ShipCountry { get; set; }
}
------解决方案--------------------修改一下
var v = list.Select(x =>
x = 5);返回 5,5,5,5,5,5,5,5,5,5 10个5
------解决方案--------------------where和select怎么会一样呢
你自己构造点数据,执行下边两个语句就明白了:
var ordByCountry = orders.Where(order => order.ShipCountry.Equals(country));
var ordByCountry1 = orders.Select(order => order.ShipCountry);
------解决方案--------------------修改下
比如说
int[] data = { 1, 2, 3, 4, 5, 6 };
以下2组代码分别是等价的:
var result = data.Where(x => x > 3).ToList();
和
var result = new List<int>();
foreach (int i in data)
{
if (i > 3) result.Add(i);
}
结果都是
4 5 6
以及
var result = data.Select(x => x > 3).ToList();
和
var result = new List<bool>();
foreach (int i in data)
{
result.Add(i > 3); //也就是 if (i > 3) result.Add(true); else result.Add(false);
}
结果都是
false false false true true ture