LINQ Learning-JoinOperators

  join...in....on

  eg1:suppliers和customers是两个数据源    

    from sup in suppliers
       join cust in customers on sup.Country equals cust.Country
       select new { Country = sup.Country, SupplierName = sup.SupplierName, CustomerName = cust.CompanyName };

  eg2:将suppliers和customers合并的数据放到cs中,key为country  

     from sup in suppliers
        join cust in customers on sup.Country equals cust.Country into cs
        select new { Key = sup.Country, Items = cs };

   eg3:先将categories和products合并的数据放到ps中,再从ps中获取数据,这里的select new{}里的p.ProductName相当于 ProductName=p.ProductName  

 string[] categories = new string[]{ 
                "Beverages", 
                "Condiments", 
                "Vegetables", 
                "Dairy Products", 
                "Seafood" };    
     from cat in categories
        join prod in products on cat equals prod.Category into ps
        from p in ps
        select new { Category = cat, p.ProductName };

   eg4:DefaultIfEmpty()会在结果集中添加上,从suppliers匹配customers为空的几条数据,不加DefaultIfEmpty()则不会有那几条数据,还可以orderby CompanyName然后判断 SupplierName是否为null  

     from sup in suppliers
        join cust in customers on sup.Country equals cust.Country into cs
        from c in cs.DefaultIfEmpty()  // DefaultIfEmpty preserves left-hand elements that have no matches on the right side 
        orderby sup.SupplierName
        select new
          {
             Country = sup.Country,
               CompanyName = c == null ? "(No customers)" : c.CompanyName,
               SupplierName = sup.SupplierName
           };

   eg5:join cust in customers on new { sup.City, sup.Country } equals new { cust.City, cust.Country } into cs,多字段对比!!

    

posted @ 2013-05-02 17:48  小飞的DD  阅读(118)  评论(0编辑  收藏  举报