複合式 LINQ.

摘要: 複合式 LINQ.

近日開始寫有關於LINQ的文章,

正巧寫到Linq To SQL,由於探索LINQ的核心概念所致,

腦中突現一個想法,"我是否可以將LINQ to SQL用的Table與LINQ to XML的XElement join起來?"

理論上,在LINQ的設計概念中,這是可行的.

static void TestCrossLinq()
{
            NORTHWND db = new NORTHWND("Data Source=.\\SQLEXPRESS;Initial Catalog=NORTHWND;Integrated Security=True");
            XDocument doc = XDocument.Load("XMLFile1.xml");


            var p = from s1 in doc.Elements("tables").Elements("table").Descendants("row")
                    join s2 in db.Customers on s1.Element("CUSTOMER_ID").Value equals s2.CustomerID
                    where s1.Parent.Attribute("name") != null &&
                          s1.Parent.Attribute("name").Value == "Orders"
                    select new XElement("Order", s1.Nodes(), new XElement("CompanyName",s2.CompanyName));
            foreach (var item in p)
            {
                foreach (var item3 in item.Elements())
                {
                    Console.WriteLine("{0} : {1}", item3.Name, item3.Value);
                    Console.WriteLine("--------------------");
                }
            }
            Console.ReadLine();
 }

 

此程式由XML中讀出Order資訊,以其CUSTOMER_ID Element中的資料來與Linq To SQL中的Table : Customers join,取出CompanyName欄位放入結果集.