当前位置:编程学习 > C#/ASP.NET >>

LINQ学习之旅---------再续

LINQ与数据库

/**/////
//  这是LINQ的与数据库部分的,很像强类型DataSet
/**/////
NorthwindDataContext db = new NorthwindDataContext();

db.Log = Console.Out;   //把SQL脚本输出到控制台

var products =
    from p in db.Products.Skip(6).Take(4)
    select new
    {
        p.ProductName,
        p.ProductID,
        p.Categories.CategoryName,
    };
//Skip()和Take()这两个方法的结合,就可以类似于储存过程分页一样
//Skip(int startIndex)从第  startIndex + 1 开始  因为它是下标
//Take(int count)一共取count条数据
//select new {p.ProductName, p.ProductID, p.Categories.CategoryName,}
//就像我们写SQL的 select 词句一样只要ProductName,ProductID,CategoryName这三列
//返回的proudcts就是只以上三个属性的对象的集合

foreach (var p in products)
{
    Console.WriteLine(p.ProductID + ":" + p.ProductName + ":" + p.CategoryName);
}
在控制台会输出一段很长的SQL词句,有兴趣自己看看吧,呵呵。

LINQ TO XML var xml = from p in db.Products.Skip(3).Take(4)
          select new XElement("Product",
              new XAttribute("ID", p.ProductID),
              new XElement("ProductName", p.ProductName),
              new XElement("CategoryName", p.Categories.CategoryName)
          );

new XDocument(new XDeclaration("1.0", "utf-8", "yes"),
    new XElement("Products", xml)).Save("C:/Products.xml");//把查询到的数据以XML文档输出到C:/Products.xml
new XDocument(new XDeclaration("1.0", "utf-8", "yes"),
    new XElement("Products", xml)).Save(Console.Out);//把查询到的数据以XML文档形式输出到控制台
Console.WriteLine(new XDocument(new XDeclaration("1.0", "utf-8", "yes"),
    new XElement("Products", xml)).ToString()); //这方法也是查询到的数据以XML文档形式输出到控制台
有了LINQ TO XML,那以后的AJAX的实现就更方便了。

var table = from p in db.Products.Skip(3).Take(4)
          select new XElement("tr",
              new XElement("td", p.ProductID),
              new XElement("td", p.ProductName),
              new XElement("td", p.Categories.CategoryName)
          );
Console.WriteLine(new XDocument(new XElement("table", table)).ToString());

转自:http://www.cnblogs.com/SouthSea/archive/2007/11/23/970440.html --------------------编程问答-------------------- 很好,学习! --------------------编程问答-------------------- 很好,VeryGood! --------------------编程问答-------------------- 不错 --------------------编程问答-------------------- 学习! --------------------编程问答-------------------- 学习! --------------------编程问答-------------------- 学习! --------------------编程问答-------------------- 学习中 ... ... --------------------编程问答-------------------- 刚开始看LINQ,不错! --------------------编程问答-------------------- IT达人群:67761614 --------------------编程问答-------------------- 学习``` --------------------编程问答-------------------- 学习... --------------------编程问答-------------------- 不错 --------------------编程问答-------------------- bu cuo --------------------编程问答-------------------- learn --------------------编程问答-------------------- 学习了。。。。。。。。。 --------------------编程问答-------------------- 我才刚接触linq,仅仅懂得皮毛,得好好学习
补充:.NET技术 ,  LINQ
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,