linq汇总
一 、let 和 into 区分
1.let 是对单个元素的引入一个变量,以便有对变量有更好的操作或筛选。可以有let。
string[] names = { "Tom", "Dick", "Harry", "Mary", "Jay" }; var query = from n in names let Vowelless = Regex.Replace(n, "[aeiou]", "") where Vowelless.Length > 2 select n; //正是因为使用了let,此时n仍然可见
2.into是把select的变量转化成一个变量,从而只可以对变量进行操作,into之前的变量已经不可见了。
string[] names = { "Tom", "Dick", "Harry", "Mary", "Jay" }; IEnumerable<string> query = from n in names select n.Replace("a", "").Replace("e", "").Replace("i", "") .Replace("o", "").Replace("u", "") into noVowel where noVowel.Length > 2 orderby noVowel select noVowel;
二、使用连接查询
// 消费者 public partial class Customer { public int ID { get; set; } public string Name { get; set; } } //订单
public partial class Order { public int ID { get; set; } public Nullable<int> CustomerID { get; set; } public DateTime OrderDate { get; set; } public decimal Price { get; set; } }
1.内连接(筛选出相交的集合)
var dataContext=new DBEntities(); #region 内连接 即有相交的才会显示出来 Customer[] customers = dataContext.Customer.ToArray(); Order[] orders = dataContext.Order.ToArray(); var query = from o in orders join c in customers on o.CustomerID equals c.ID select c.Name + o.OrderDate; #endregion
2.外连接(左右连接left join on)
var query = from o in customers join c in orders on o.ID equals c.CustomerID into IEOrder from itemOrder in IEOrder.DefaultIfEmpty() select new { name = o.Name, orderDate = itemOrder != null ? itemOrder.OrderDate : null };