您的位置:知识库 »

LINQ to SQL语句(2)之Select/Distinct

作者: 李永京  来源: 博客园  发布时间: 2008-09-18 14:46  阅读: 83217 次  推荐: 13   原文链接   [收藏]  
摘要:这个系列的第二篇,了解Select/Distinct操作符用法。
[1] Select介绍1
[2] Select介绍2
[3] Select介绍3和Distinct介绍

系列文章导航:

LINQ to SQL语句(1)之Where

LINQ to SQL语句(2)之Select/Distinct

LINQ to SQL语句(3)之Count/Sum/Min/Max/Avg

LINQ to SQL语句(4)之Join

LINQ to SQL语句(5)之Order By

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语句(10)之Insert

LINQ to SQL语句(11)之Update

LINQ to SQL语句(12)之Delete和使用Attach

LINQ to SQL语句(13)之开放式并发控制和事务

LINQ to SQL语句(14)之Null语义和DateTime

LINQ to SQL语句(15)之String

LINQ to SQL语句(16)之对象标识

LINQ to SQL语句(17)之对象加载

LINQ to SQL语句(18)之运算符转换

LINQ to SQL语句(19)之ADO.NET与LINQ to SQL

LINQ to SQL语句(20)之存储过程

LINQ to SQL语句(21)之用户定义函数

LINQ to SQL语句(22)之DataContext

LINQ to SQL语句(23)之动态查询

LINQ to SQL语句(24)之视图

LINQ to SQL语句(25)之继承

LINQ简介

adsfsaf


 

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();

语句描述:查询顾客覆盖的国家。

13
5
标签:LINQ LINQ to SQL

热门文章

    最新文章

      最新新闻

        热门新闻