LINQ to SQL语句(2)之Select/Distinct
系列文章导航:
LINQ to SQL语句(2)之Select/Distinct
LINQ to SQL语句(3)之Count/Sum/Min/Max/Avg
LINQ to SQL语句(6)之Group By/Having
LINQ to SQL语句(7)之Exists/In/Any/All/Contains
LINQ to SQL语句(8)之Concat/Union/Intersect/Except
LINQ to SQL语句(9)之Top/Bottom和Paging和SqlMethods
LINQ to SQL语句(12)之Delete和使用Attach
LINQ to SQL语句(14)之Null语义和DateTime
LINQ to SQL语句(19)之ADO.NET与LINQ to SQL
7.嵌套类型形式:
说明:返回的对象集中的每个对象DiscountedProducts属性中,又包含一个集合。也就是每个对象也是一个集合类。
var q = from o in db.Orders select new { o.OrderID, DiscountedProducts = from od in o.OrderDetails where od.Discount > 0.0 select od, FreeShippingDiscount = o.Freight };
语句描述:使用嵌套查询返回所有订单及其OrderID 的序列、打折订单中项目的子序列以及免送货所省下的金额。
8.本地方法调用形式(LocalMethodCall):
这个例子在查询中调用本地方法PhoneNumberConverter将电话号码转换为国际格式。
var q = from c in db.Customers where c.Country == "UK" || c.Country == "USA" select new { c.CustomerID, c.CompanyName, Phone = c.Phone, InternationalPhone = PhoneNumberConverter(c.Country, c.Phone) };
PhoneNumberConverter方法如下:
public string PhoneNumberConverter(string Country, string Phone) { Phone = Phone.Replace(" ", "").Replace(")", ")-"); switch (Country) { case "USA": return "1-" + Phone; case "UK": return "44-" + Phone; default: return Phone; } }
下面也是使用了这个方法将电话号码转换为国际格式并创建XDocument
XDocument doc = new XDocument( new XElement("Customers", from c in db.Customers where c.Country == "UK" || c.Country == "USA" select (new XElement("Customer", new XAttribute("CustomerID", c.CustomerID), new XAttribute("CompanyName", c.CompanyName), new XAttribute("InterationalPhone", PhoneNumberConverter(c.Country, c.Phone)) ))));
9.Distinct形式:
说明:筛选字段中不相同的值。用于查询不重复的结果集。生成SQL语句为:SELECT DISTINCT [City] FROM [Customers]
var q = ( from c in db.Customers select c.City ) .Distinct();
语句描述:查询顾客覆盖的国家。