Linq 入門

1.簡單形式:
var q =
  from c in db.Customers
  select c.ContactName;

 

 

2.匿名類型形式:

var q =
    from c in db.Customers
    select new {c.ContactName, c.Phone};

var q =
    from e in db.Employees
    select new {Name = e.FirstName + " " + e.LastName, Phone = e.HomePhone};

var q =
    from p in db.Products
    select new {p.ProductID, HalfPrice = p.UnitPrice / 2};

3.帶條件形式:
var q =
    from p in db.Products
    select new {p.ProductName, Availability = p.UnitsInStock - p.UnitsOnOrder < 0 ? "Out Of Stock": "In Stock"};

4.指定類型形式:
var q =
    from e in db.Employees
    select new Name {FirstName = e.FirstName, LastName = e.LastName};

5.過濾類型形式:
var q =
    from c in db.Customers
    where c.City == "London"
    select c.ContactName;

6.shaped類型形式:
var q =
    from c in db.Customers
    select new {
      c.CustomerID,
      CompanyInfo = new {c.CompanyName, c.City, c.Country},
      ContactInfo = new {c.ContactName, c.ContactTitle}
  };


7.嵌套類型形式:
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
  };

8.LocalMethodCall形式:
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) };
 

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形式:
var q = (
    from c in db.Customers
    select c.City )
    .Distinct();

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章