﻿# 好用的 Linq Samples and the Sample Query Explorer

上次在微軟 Windows Server 2008 與 Visual Studio 2008聯合上市發表會看到有講師執行一個 LINQ Project Sample Query Explorer，覺得很好用，因為他把所有 LINQ 的範例放在程式裡，點選之後就會出現語法，還可以執行，真是學習 LINQ 的絕佳教材。

![LINQ Project Sample Query Explorer](https://stwillblogassets.blob.core.windows.net/files/images/external/stwillblogassets.blob.core.windows.net/4824632f4bff8e720a7c-Screenshot-080506-000900_3.png)

不過我找了好久才找到，原來這個程式是附在 Visual Studio 2008 裡面的，你只要到 C:\\Program Files\\Microsoft Visual Studio 9.0\\Samples\\1033 目錄下就可以看到  CSharpSamples.zip 這個檔案，解壓縮之後進入 LinqSamples 目錄開啟 LinqSamples.sln 方案，再按下 F5 就可以執行了。

而這個 CSharpSample 範例也是一個 [MSDN Code Gallery](http://code.msdn.microsoft.com/) 的專案，專案的網站在此：[https://web.archive.org/web/20080128114405/http://code.msdn.microsoft.com:80/csharpsamples](https://web.archive.org/web/20080128114405/http://code.msdn.microsoft.com:80/csharpsamples "http://code.msdn.microsoft.com/csharpsamples")，你可以下載最新版的範例後，將下載的原始碼將原本的解壓縮的目錄覆蓋過去即可。

不過，在範例 XLinq55 中的程式有 Bug，執行的結果都查不到任何資料！Output 都會是 <CustomerOrders />

請開啟 LinqSamples\\SampleQueries\\LinqToXmlSamples.cs 檔案，並找到 XLinq55() 方法（應該在第1056行），整個換成以下的程式碼即可：

```
[Category("Grouping")]
[Title("Group orders by customer")]
[Description("Group orders by customer and return all customers (+ orders) for customers who have more than 25 orders ")]
public void XLinq55() {
    XDocument customers = XDocument.Load(dataPath + "nw_customers.xml");
    XDocument orders = XDocument.Load(dataPath + "nw_orders.xml");
    XElement custOrder = new XElement("CustomerOrders",
        from
            order in orders.Descendants("Orders")
        group order by
            order.Element("CustomerID").Value into cust_orders
        where
            cust_orders.Count() > 25
        select
            new XElement("Customer",
                new XAttribute("CustomerID", cust_orders.Key),
                from
                    customer in customers.Descendants("Customers")
                where
                    (string)customer.Attribute("CustomerID") == (string)cust_orders.Key
                select
                    customer.Nodes(),
                cust_orders));

    Console.WriteLine(custOrder);
}
```

**相關連結**

-   [C# Samples for Visual Studio 2008](https://web.archive.org/web/20080128114405/http://code.msdn.microsoft.com:80/csharpsamples)
-   [Visual Studio 2008 Samples](https://learn.microsoft.com/en-us/samples/browse/)
-   [LINQ to XML: Grouping and Aggregation Gotchas, Part I](http://oakleafblog.blogspot.com/2008/01/linq-to-xml-grouping-and-aggregation.html)
-   [Visual Studio 2008 Linq Samples and the Sample Query Explorer](http://realworldsa.dotnetdevelopersjournal.com/visualstudio2008linqsamplesqueryvisualizer.htm)
