diff --git a/.openpublishing.redirection.json b/.openpublishing.redirection.json index 9fc4e87efb2c3..eb459b619c19f 100644 --- a/.openpublishing.redirection.json +++ b/.openpublishing.redirection.json @@ -1553,6 +1553,26 @@ "redirect_url": "/dotnet/standard/linq/write-query-finds-elements-based-context", "redirect_document_id": true }, + { + "source_path": "docs/csharp/programming-guide/concepts/linq/how-to-control-the-type-of-a-projection.md", + "redirect_url": "/dotnet/standard/linq/control-type-projection", + "redirect_document_id": true + }, + { + "source_path": "docs/csharp/programming-guide/concepts/linq/how-to-project-a-new-type-linq-to-xml.md", + "redirect_url": "/dotnet/standard/linq/project-new-type", + "redirect_document_id": true + }, + { + "source_path": "docs/csharp/programming-guide/concepts/linq/how-to-transform-the-shape-of-an-xml-tree.md", + "redirect_url": "/dotnet/standard/linq/transform-shape-xml-tree", + "redirect_document_id": true + }, + { + "source_path": "docs/csharp/programming-guide/concepts/linq/how-to-work-with-dictionaries-using-linq-to-xml.md", + "redirect_url": "/dotnet/standard/linq/work-dictionaries-linq-xml", + "redirect_document_id": true + }, { "source_path": "docs/csharp/programming-guide/concepts/threading/how-to-use-a-thread-pool.md", "redirect_url": "/dotnet/api/system.threading.threadpool.queueuserworkitem" @@ -4864,6 +4884,26 @@ "redirect_url": "/dotnet/standard/linq/write-query-finds-elements-based-context", "redirect_document_id": false }, + { + "source_path": "docs/visual-basic/programming-guide/concepts/linq/how-to-control-the-type-of-a-projection.md", + "redirect_url": "/dotnet/standard/linq/control-type-projection", + "redirect_document_id": false + }, + { + "source_path": "docs/visual-basic/programming-guide/concepts/linq/how-to-project-a-new-type-linq-to-xml.md", + "redirect_url": "/dotnet/standard/linq/project-new-type", + "redirect_document_id": false + }, + { + "source_path": "docs/visual-basic/programming-guide/concepts/linq/how-to-transform-the-shape-of-an-xml-tree.md", + "redirect_url": "/dotnet/standard/linq/transform-shape-xml-tree", + "redirect_document_id": false + }, + { + "source_path": "docs/visual-basic/programming-guide/concepts/linq/how-to-work-with-dictionaries-using-linq-to-xml.md", + "redirect_url": "/dotnet/standard/linq/work-dictionaries-linq-xml", + "redirect_document_id": false + }, { "source_path": "docs/visual-basic/programming-guide/concepts/threading/how-to-use-a-thread-pool.md", "redirect_url": "/dotnet/api/system.threading.threadpool.queueuserworkitem" diff --git a/docs/csharp/programming-guide/concepts/linq/how-to-control-the-type-of-a-projection.md b/docs/csharp/programming-guide/concepts/linq/how-to-control-the-type-of-a-projection.md deleted file mode 100644 index df12ce87471d8..0000000000000 --- a/docs/csharp/programming-guide/concepts/linq/how-to-control-the-type-of-a-projection.md +++ /dev/null @@ -1,68 +0,0 @@ ---- -title: "How to control the type of a projection (C#)" -ms.date: 07/20/2015 -ms.assetid: e4db6b7e-4cc9-4c8f-af85-94acf32aa348 ---- -# How to control the type of a projection (C#) -Projection is the process of taking one set of data, filtering it, changing its shape, and even changing its type. Most query expressions perform projections. Most of the query expressions shown in this section evaluate to of , but you can control the type of the projection to create collections of other types. This topic shows how to do this. - -## Example - The following example defines a new type, `Customer`. The query expression then instantiates new `Customer` objects in the `Select` clause. This causes the type of the query expression to be of `Customer`. - - This example uses the following XML document: [Sample XML File: Customers and Orders (LINQ to XML)](./sample-xml-file-customers-and-orders-linq-to-xml-2.md). - -```csharp -public class Customer -{ - private string customerID; - public string CustomerID{ get{return customerID;} set{customerID = value;}} - - private string companyName; - public string CompanyName{ get{return companyName;} set{companyName = value;}} - - private string contactName; - public string ContactName { get{return contactName;} set{contactName = value;}} - - public Customer(string customerID, string companyName, string contactName) - { - CustomerID = customerID; - CompanyName = companyName; - ContactName = contactName; - } - - public override string ToString() - { - return $"{this.customerID}:{this.companyName}:{this.contactName}"; - } -} - -class Program -{ - static void Main(string[] args) - { - XElement custOrd = XElement.Load("CustomersOrders.xml"); - IEnumerable custList = - from el in custOrd.Element("Customers").Elements("Customer") - select new Customer( - (string)el.Attribute("CustomerID"), - (string)el.Element("CompanyName"), - (string)el.Element("ContactName") - ); - foreach (Customer cust in custList) - Console.WriteLine(cust); - } -} -``` - - This code produces the following output: - -```output -GREAL:Great Lakes Food Market:Howard Snyder -HUNGC:Hungry Coyote Import Store:Yoshi Latimer -LAZYK:Lazy K Kountry Store:John Steel -LETSS:Let's Stop N Shop:Jaime Yorres -``` - -## See also - -- diff --git a/docs/csharp/programming-guide/concepts/linq/how-to-project-a-new-type-linq-to-xml.md b/docs/csharp/programming-guide/concepts/linq/how-to-project-a-new-type-linq-to-xml.md deleted file mode 100644 index 2f74a2bed2d72..0000000000000 --- a/docs/csharp/programming-guide/concepts/linq/how-to-project-a-new-type-linq-to-xml.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -title: "How to project a new type (LINQ to XML) (C#)" -ms.date: 07/20/2015 -ms.assetid: 48145cf9-1e0b-4e73-bbfd-28fc04800dc4 ---- -# How to project a new type (LINQ to XML) (C#) - -Other examples in this section have shown queries that return results as of , of `string`, and of `int`. These are common result types, but they are not appropriate for every scenario. In many cases you will want your queries to return an of some other type. - -## Example - -This example shows how to instantiate objects in the `select` clause. The code first defines a new class with a constructor, and then modifies the `select` statement so that the expression is a new instance of the new class. - -This example uses the following XML document: [Sample XML File: Typical Purchase Order (LINQ to XML)](./sample-xml-file-typical-purchase-order-linq-to-xml-1.md). - -```csharp -class NameQty -{ - public string name; - public int qty; - public NameQty(string n, int q) - { - name = n; - qty = q; - } -}; - -class Program { - public static void Main() - { - XElement po = XElement.Load("PurchaseOrder.xml"); - - IEnumerable nqList = - from n in po.Descendants("Item") - select new NameQty( - (string)n.Element("ProductName"), - (int)n.Element("Quantity") - ); - - foreach (NameQty n in nqList) - Console.WriteLine(n.name + ":" + n.qty); - } -} -``` - -This example uses the method that was introduced in the topic [How to retrieve a single child element (LINQ to XML) (C#)](how-to-retrieve-a-single-child-element-linq-to-xml.md). It also uses casts to retrieve the values of the elements that are returned by the method. - -This example produces the following output: - -```output -Lawnmower:1 -Baby Monitor:2 -``` diff --git a/docs/csharp/programming-guide/concepts/linq/how-to-transform-the-shape-of-an-xml-tree.md b/docs/csharp/programming-guide/concepts/linq/how-to-transform-the-shape-of-an-xml-tree.md deleted file mode 100644 index 1f68df12bb033..0000000000000 --- a/docs/csharp/programming-guide/concepts/linq/how-to-transform-the-shape-of-an-xml-tree.md +++ /dev/null @@ -1,133 +0,0 @@ ---- -title: "How to transform the shape of an XML tree (C#)" -ms.date: 07/20/2015 -ms.assetid: 93c5d426-dea2-4709-a991-60204de42e8f ---- -# How to transform the shape of an XML tree (C#) -The *shape* of an XML document refers to its element names, attribute names, and the characteristics of its hierarchy. - - Sometimes you will have to change the shape of an XML document. For example, you might have to send an existing XML document to another system that requires different element and attribute names. You could go through the document, deleting and renaming elements as required, but using functional construction results in more readable and maintainable code. For more information about functional construction, see [Functional Construction (LINQ to XML) (C#)](./functional-construction-linq-to-xml.md). - - The first example changes the organization of the XML document. It moves complex elements from one location in the tree to another. - - The second example in this topic creates an XML document with a different shape than the source document. It changes the casing of the element names, renames some elements, and leaves some elements from the source tree out of the transformed tree. - -## Example - The following code changes the shape of an XML file using embedded query expressions. - - The source XML document in this example contains a `Customers` element under the `Root` element that contains all customers. It also contains an `Orders` element under the `Root` element that contains all orders. This example creates a new XML tree in which the orders for each customer are contained in an `Orders` element within the `Customer` element. The original document also contains a `CustomerID` element in the `Order` element; this element will be removed from the re-shaped document. - - This example uses the following XML document: [Sample XML File: Customers and Orders (LINQ to XML)](./sample-xml-file-customers-and-orders-linq-to-xml-2.md). - -```csharp -XElement co = XElement.Load("CustomersOrders.xml"); -XElement newCustOrd = - new XElement("Root", - from cust in co.Element("Customers").Elements("Customer") - select new XElement("Customer", - cust.Attributes(), - cust.Elements(), - new XElement("Orders", - from ord in co.Element("Orders").Elements("Order") - where (string)ord.Element("CustomerID") == (string)cust.Attribute("CustomerID") - select new XElement("Order", - ord.Attributes(), - ord.Element("EmployeeID"), - ord.Element("OrderDate"), - ord.Element("RequiredDate"), - ord.Element("ShipInfo") - ) - ) - ) - ); -Console.WriteLine(newCustOrd); -``` - - This code produces the following output: - -```xml - - - Great Lakes Food Market - Howard Snyder - Marketing Manager - (503) 555-7555 - -
2732 Baker Blvd.
- Eugene - OR - 97403 - USA -
- -
- - Hungry Coyote Import Store - Yoshi Latimer - Sales Representative - (503) 555-6874 - (503) 555-2376 - -
City Center Plaza 516 Main St.
- Elgin - OR - 97827 - USA -
- -
- . . . -``` - -## Example - This example renames some elements and converts some attributes to elements. - - The code calls `ConvertAddress`, which returns a list of objects. The argument to the method is a query that determines the `Address` complex element where the `Type` attribute has a value of `"Shipping"`. - - This example uses the following XML document: [Sample XML File: Typical Purchase Order (LINQ to XML)](./sample-xml-file-typical-purchase-order-linq-to-xml-1.md). - -```csharp -static IEnumerable ConvertAddress(XElement add) -{ - List fragment = new List() { - new XElement("NAME", (string)add.Element("Name")), - new XElement("STREET", (string)add.Element("Street")), - new XElement("CITY", (string)add.Element("City")), - new XElement("ST", (string)add.Element("State")), - new XElement("POSTALCODE", (string)add.Element("Zip")), - new XElement("COUNTRY", (string)add.Element("Country")) - }; - return fragment; -} - -static void Main(string[] args) -{ - XElement po = XElement.Load("PurchaseOrder.xml"); - XElement newPo = new XElement("PO", - new XElement("ID", (string)po.Attribute("PurchaseOrderNumber")), - new XElement("DATE", (DateTime)po.Attribute("OrderDate")), - ConvertAddress( - (from el in po.Elements("Address") - where (string)el.Attribute("Type") == "Shipping" - select el) - .First() - ) - ); - Console.WriteLine(newPo); -} -``` - - This code produces the following output: - -```xml - - 99503 - 1999-10-20T00:00:00 - Ellen Adams - 123 Maple Street - Mill Valley - CA - 10999 - USA - -``` diff --git a/docs/csharp/programming-guide/concepts/linq/how-to-work-with-dictionaries-using-linq-to-xml.md b/docs/csharp/programming-guide/concepts/linq/how-to-work-with-dictionaries-using-linq-to-xml.md deleted file mode 100644 index 7bc0f880014ed..0000000000000 --- a/docs/csharp/programming-guide/concepts/linq/how-to-work-with-dictionaries-using-linq-to-xml.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -title: "How to work with dictionaries using LINQ to XML (C#)" -ms.date: 07/20/2015 -ms.assetid: 57bcefe3-8433-4d3b-935a-511c9bcbdfa8 ---- -# How to work with dictionaries using LINQ to XML (C#) -It is often convenient to convert varieties of data structures to XML, and XML back to other data structures. This topic shows a specific implementation of this general approach by converting a to XML and back. - -## Example - This example uses a form of functional construction in which a query projects new objects, and the resulting collection is passed as an argument to the constructor of the Root object. - -```csharp -Dictionary dict = new Dictionary(); -dict.Add("Child1", "Value1"); -dict.Add("Child2", "Value2"); -dict.Add("Child3", "Value3"); -dict.Add("Child4", "Value4"); -XElement root = new XElement("Root", - from keyValue in dict - select new XElement(keyValue.Key, keyValue.Value) -); -Console.WriteLine(root); -``` - - This code produces the following output: - -```xml - - Value1 - Value2 - Value3 - Value4 - -``` - -## Example - The following code creates a dictionary from XML. - -```csharp -XElement root = new XElement("Root", - new XElement("Child1", "Value1"), - new XElement("Child2", "Value2"), - new XElement("Child3", "Value3"), - new XElement("Child4", "Value4") -); - -Dictionary dict = new Dictionary(); -foreach (XElement el in root.Elements()) - dict.Add(el.Name.LocalName, el.Value); -foreach (string str in dict.Keys) - Console.WriteLine("{0}:{1}", str, dict[str]); -``` - - This code produces the following output: - -```output -Child1:Value1 -Child2:Value2 -Child3:Value3 -Child4:Value4 -``` diff --git a/docs/standard/linq/control-type-projection.md b/docs/standard/linq/control-type-projection.md new file mode 100644 index 0000000000000..c6279f84f209a --- /dev/null +++ b/docs/standard/linq/control-type-projection.md @@ -0,0 +1,135 @@ +--- +title: How to control the type of a projection - LINQ to XML +description: You can control the type of collection that your query returns; it need not be an IEnumerable of XElements. +ms.date: 07/20/2015 +dev_langs: + - "csharp" + - "vb" +ms.assetid: e4db6b7e-4cc9-4c8f-af85-94acf32aa348 +--- +# How to control the type of a projection (LINQ to XML) + +*Projection* is the process of filtering a set of data, changing its shape and perhaps its type. Most query expressions do projections. Most of the query expressions in this section evaluate to of , but you can create collections of other types. This article shows how to do this. + +## Example: Define a new type and create a query that creates an IEnumerable of that type + +The following example defines a new type, `Customer`, and the query expression instantiates new `Customer` objects in the `Select` clause. This causes the type of the query expression to be of `Customer`. The example uses XML document [Sample XML file: Customers and orders](sample-xml-file-customers-orders.md). + +```csharp +public class Customer +{ + private string customerID; + public string CustomerID{ get{return customerID;} set{customerID = value;}} + + private string companyName; + public string CompanyName{ get{return companyName;} set{companyName = value;}} + + private string contactName; + public string ContactName { get{return contactName;} set{contactName = value;}} + + public Customer(string customerID, string companyName, string contactName) + { + CustomerID = customerID; + CompanyName = companyName; + ContactName = contactName; + } + + public override string ToString() + { + return $"{this.customerID}:{this.companyName}:{this.contactName}"; + } +} + +class Program +{ + static void Main(string[] args) + { + XElement custOrd = XElement.Load("CustomersOrders.xml"); + IEnumerable custList = + from el in custOrd.Element("Customers").Elements("Customer") + select new Customer( + (string)el.Attribute("CustomerID"), + (string)el.Element("CompanyName"), + (string)el.Element("ContactName") + ); + foreach (Customer cust in custList) + Console.WriteLine(cust); + } + + +} +``` + +```vb +Public Class Customer + Private customerIDValue As String + Public Property CustomerID() As String + Get + Return customerIDValue + End Get + Set(ByVal value As String) + customerIDValue = value + End Set + End Property + + Private companyNameValue As String + Public Property CompanyName() As String + Get + Return companyNameValue + End Get + Set(ByVal value As String) + companyNameValue = value + End Set + End Property + + Private contactNameValue As String + Public Property ContactName() As String + Get + Return contactNameValue + End Get + Set(ByVal value As String) + contactNameValue = value + End Set + End Property + + Public Sub New(ByVal customerID As String, _ + ByVal companyName As String, _ + ByVal contactName As String) + CustomerIDValue = customerID + CompanyNameValue = companyName + ContactNameValue = contactName + End Sub + + Public Overrides Function ToString() As String + Return String.Format("{0}:{1}:{2}", Me.CustomerID, Me.CompanyName, Me.ContactName) + End Function +End Class + +Sub Main() + Dim custOrd As XElement = XElement.Load("CustomersOrders.xml") + Dim custList As IEnumerable(Of Customer) = _ + From el In custOrd.. _ + Select New Customer( _ + el.@, _ + el..Value, _ + el..Value _ + ) + For Each cust In custList + Console.WriteLine(cust) + Next +End Sub +``` + +The example produces this output: + +```output +GREAL:Great Lakes Food Market:Howard Snyder +HUNGC:Hungry Coyote Import Store:Yoshi Latimer +LAZYK:Lazy K Kountry Store:John Steel +LETSS:Let's Stop N Shop:Jaime Yorres +``` + +## See also + +- +- [Projections and Transformations (LINQ to XML) (Visual Basic)](../../visual-basic/programming-guide/concepts/linq/projections-and-transformations-linq-to-xml.md) diff --git a/docs/standard/linq/project-new-type.md b/docs/standard/linq/project-new-type.md new file mode 100644 index 0000000000000..af99a0dc72f6a --- /dev/null +++ b/docs/standard/linq/project-new-type.md @@ -0,0 +1,84 @@ +--- +title: How to project a new type - LINQ to XML +description: Your query can return an IEnumerable of a type other than the common ones. This article shows how in an example. +ms.date: 07/20/2015 +dev_langs: + - "csharp" + - "vb" +ms.assetid: 48145cf9-1e0b-4e73-bbfd-28fc04800dc4 +--- + +# How to project a new type (LINQ to XML) + +Other examples in this section have shown queries that return results as of , of `string`, and of `int`. These are common result types, but they are not appropriate for every scenario. In many cases you will want your queries to return an of some other type. + +## Example: Define a new type and have the `select` statement create an instance of the type + +This example shows how to instantiate objects in the `select` clause. The code first invokes a constructor to define a new class, and then modifies the `select` statement so that the expression is a new instance of the new class. The example uses XML document [Sample XML file: Typical purchase order](sample-xml-file-typical-purchase-order.md). + +```csharp +class NameQty +{ + public string name; + public int qty; + public NameQty(string n, int q) + { + name = n; + qty = q; + } +}; + +class Program { + public static void Main() + { + XElement po = XElement.Load("PurchaseOrder.xml"); + + IEnumerable nqList = + from n in po.Descendants("Item") + select new NameQty( + (string)n.Element("ProductName"), + (int)n.Element("Quantity") + ); + + foreach (NameQty n in nqList) + Console.WriteLine(n.name + ":" + n.qty); + } +} +``` + +```vb +Public Class NameQty + Public name As String + Public qty As Integer + Public Sub New(ByVal n As String, ByVal q As Integer) + name = n + qty = q + End Sub +End Class + +Public Class Program + Shared Sub Main() + Dim po As XElement = XElement.Load("PurchaseOrder.xml") + + Dim nqList As IEnumerable(Of NameQty) = _ + From n In po... _ + Select New NameQty( _ + n..Value, CInt(n..Value)) + + For Each n As NameQty In nqList + Console.WriteLine(n.name & ":" & n.qty) + Next + End Sub +End Class +``` + +This example uses the method that was introduced in the topic [How to retrieve a single child element](retrieve-single-child-element.md). It also uses casts to retrieve the values of the elements that are returned by the method. + +The example produces this output: + +```output +Lawnmower:1 +Baby Monitor:2 +``` + +- [Projections and Transformations (LINQ to XML) (Visual Basic)](../../visual-basic/programming-guide/concepts/linq/projections-and-transformations-linq-to-xml.md) diff --git a/docs/standard/linq/transform-shape-xml-tree.md b/docs/standard/linq/transform-shape-xml-tree.md new file mode 100644 index 0000000000000..656f4b3e1374f --- /dev/null +++ b/docs/standard/linq/transform-shape-xml-tree.md @@ -0,0 +1,198 @@ +--- +title: How to transform the shape of an XML tree - LINQ to XML +description: You can use functional construction to change the shape of an XML document; that is, to retain the data but change such things as element names, attribute names, and hierarchy. +ms.date: 07/20/2015 +dev_langs: + - "csharp" + - "vb" +ms.assetid: 93c5d426-dea2-4709-a991-60204de42e8f +--- + +# How to transform the shape of an XML tree (LINQ to XML) + +The *shape* of an XML document refers to its element names, attribute names, and the characteristics of its hierarchy. + +Sometimes you will have to change the shape of an XML document. For example, you might have to send an existing XML document to another system that requires different element and attribute names. You could go through the document, deleting and renaming elements as required, but using functional construction results in more readable and maintainable code. For more information about functional construction, see [Functional construction](functional-construction.md). + +The first example in this article changes the organization of an XML document. It moves complex elements from one location in the tree to another. + +The second example creates an XML document whose shape differs from that of the source document. It omits some elements, renames others, and changes the casing of the element names. + +## Example: Use embedded query expressions to change the shape of an XML tree + +The following example changes the shape of an XML file using embedded query expressions. + +The source XML document for this example, [Sample XML file: Customers and orders](sample-xml-file-customers-orders.md), contains a `Customers` element under the `Root` element that contains all customers. It also contains an `Orders` element under the `Root` element that contains all orders. The example creates a new XML tree in which the orders for each customer are contained in an `Orders` element within the `Customer` element. The original document also contains a `CustomerID` element in the `Order` element; this element is omitted from the new tree. + +```csharp +XElement co = XElement.Load("CustomersOrders.xml"); +XElement newCustOrd = + new XElement("Root", + from cust in co.Element("Customers").Elements("Customer") + select new XElement("Customer", + cust.Attributes(), + cust.Elements(), + new XElement("Orders", + from ord in co.Element("Orders").Elements("Order") + where (string)ord.Element("CustomerID") == (string)cust.Attribute("CustomerID") + select new XElement("Order", + ord.Attributes(), + ord.Element("EmployeeID"), + ord.Element("OrderDate"), + ord.Element("RequiredDate"), + ord.Element("ShipInfo") + ) + ) + ) + ); +Console.WriteLine(newCustOrd); +``` + + ```vb +Dim co As XElement = XElement.Load("CustomersOrders.xml") +Dim newCustOrd = _ + + <%= From cust In co.. _ + Select _ + + <%= cust.Attributes() %> + <%= cust.Elements() %> + + <%= From ord In co.. _ + Where ord..Value = cust.@CustomerID _ + Select _ + + <%= ord.Attributes() %> + <%= ord. %> + <%= ord. %> + <%= ord. %> + <%= ord. %> + _ + %> + + _ + %> + +Console.WriteLine(newCustOrd) +``` + +The example produces this output: + +```xml + + + Great Lakes Food Market + Howard Snyder + Marketing Manager + (503) 555-7555 + +
2732 Baker Blvd.
+ Eugene + OR + 97403 + USA +
+ +
+ + Hungry Coyote Import Store + Yoshi Latimer + Sales Representative + (503) 555-6874 + (503) 555-2376 + +
City Center Plaza 516 Main St.
+ Elgin + OR + 97827 + USA +
+ +
+ . . . +``` + +## Example: Create a document whose shape differs from that of the source document + +This example renames some elements and converts some attributes to elements. It calls `ConvertAddress`, which returns a list of objects. The argument to the method is a query that determines the `Address` complex element where the `Type` attribute has a value of `"Shipping"`. The example uses XML document [Sample XML file: Typical purchase order](sample-xml-file-typical-purchase-order.md). + +```csharp +static IEnumerable ConvertAddress(XElement add) +{ + List fragment = new List() { + new XElement("NAME", (string)add.Element("Name")), + new XElement("STREET", (string)add.Element("Street")), + new XElement("CITY", (string)add.Element("City")), + new XElement("ST", (string)add.Element("State")), + new XElement("POSTALCODE", (string)add.Element("Zip")), + new XElement("COUNTRY", (string)add.Element("Country")) + }; + return fragment; +} + +static void Main(string[] args) +{ + XElement po = XElement.Load("PurchaseOrder.xml"); + XElement newPo = new XElement("PO", + new XElement("ID", (string)po.Attribute("PurchaseOrderNumber")), + new XElement("DATE", (DateTime)po.Attribute("OrderDate")), + ConvertAddress( + (from el in po.Elements("Address") + where (string)el.Attribute("Type") == "Shipping" + select el) + .First() + ) + ); + Console.WriteLine(newPo); +} +``` + +```vb +Function ConvertAddress(ByVal add As XElement) As IEnumerable(Of XElement) + Dim fragment = New List(Of XElement) + fragment.Add(<%= add..Value %>) + fragment.Add(<%= add..Value %>) + fragment.Add(<%= add..Value %>) + fragment.Add(<%= add..Value %>) + fragment.Add(<%= add..Value %>) + fragment.Add(<%= add..Value %>) + Return fragment +End Function + +Sub Main() + Dim po As XElement = XElement.Load("PurchaseOrder.xml") + Dim newPo As XElement = _ + + <%= po.@PurchaseOrderNumber %> + <%= CDate(po.@OrderDate) %> + <%= _ + ConvertAddress( _ + (From el In po.
_ + Where el.@Type = "Shipping" _ + Select el) _ + .First() _ + ) _ + %> + + Console.WriteLine(newPo) +End Sub +``` + +The example produces this output: + +```xml + + 99503 + 1999-10-20T00:00:00 + Ellen Adams + 123 Maple Street + Mill Valley + CA + 10999 + USA + +``` + +## See also + +- [Projections and Transformations (LINQ to XML) (Visual Basic)](../../visual-basic/programming-guide/concepts/linq/projections-and-transformations-linq-to-xml.md) diff --git a/docs/standard/linq/work-dictionaries-linq-xml.md b/docs/standard/linq/work-dictionaries-linq-xml.md new file mode 100644 index 0000000000000..3257ae5121e5c --- /dev/null +++ b/docs/standard/linq/work-dictionaries-linq-xml.md @@ -0,0 +1,109 @@ +--- +title: How to work with dictionaries using LINQ to XML - LINQ to XML +description: You can convert many kinds of data structures to XML, and you can convert XML to structures. Here is an example that converts a Generic.Dictionary to XML and back. +ms.date: 07/20/2015 +dev_langs: + - "csharp" + - "vb" +ms.assetid: 57bcefe3-8433-4d3b-935a-511c9bcbdfa8 +--- + +# How to work with dictionaries using LINQ to XML + +It's often convenient to convert data structures of various kinds to XML, and then from XML to other data structures. This article shows a conversion of a to XML and back. + +## Example: Create a Dictionary and convert its contents to XML + +This first example creates a , and then converts it to XML. + +This C# version of the example uses a form of functional construction in which a query projects new objects, and the resulting collection is passed as an argument to the constructor of the Root object. + +The Visual Basic version uses XML literals and a query in an embedded expression. The query projects new objects which then become the new content for the `Root` object. + +```csharp +Dictionary dict = new Dictionary(); +dict.Add("Child1", "Value1"); +dict.Add("Child2", "Value2"); +dict.Add("Child3", "Value3"); +dict.Add("Child4", "Value4"); +XElement root = new XElement("Root", + from keyValue in dict + select new XElement(keyValue.Key, keyValue.Value) +); +Console.WriteLine(root); +``` + +```vb +Dim dict As Dictionary(Of String, String) = New Dictionary(Of String, String)() +dict.Add("Child1", "Value1") +dict.Add("Child2", "Value2") +dict.Add("Child3", "Value3") +dict.Add("Child4", "Value4") +Dim root As XElement = _ + + <%= From keyValue In dict _ + Select New XElement(keyValue.Key, keyValue.Value) %> + +Console.WriteLine(root) +``` + +The example produces this output: + +```xml + + Value1 + Value2 + Value3 + Value4 + +``` + +## Example: Create a dictionary and load it from XML data + +The next example creates a dictionary loads loads it from XML data. + +```csharp +XElement root = new XElement("Root", + new XElement("Child1", "Value1"), + new XElement("Child2", "Value2"), + new XElement("Child3", "Value3"), + new XElement("Child4", "Value4") +); + +Dictionary dict = new Dictionary(); +foreach (XElement el in root.Elements()) + dict.Add(el.Name.LocalName, el.Value); +foreach (string str in dict.Keys) + Console.WriteLine("{0}:{1}", str, dict[str]); +``` + +```vb +Dim root As XElement = _ + + Value1 + Value2 + Value3 + Value4 + + +Dim dict As Dictionary(Of String, String) = New Dictionary(Of String, String) +For Each el As XElement In root.Elements + dict.Add(el.Name.LocalName, el.Value) +Next +For Each str As String In dict.Keys + Console.WriteLine("{0}:{1}", str, dict(str)) +Next +``` + +The example produces this output: + +```output +Child1:Value1 +Child2:Value2 +Child3:Value3 +Child4:Value4 +``` + +## See also + +- [Projections and Transformations (LINQ to XML) (Visual Basic)](../../visual-basic/programming-guide/concepts/linq/projections-and-transformations-linq-to-xml.md) diff --git a/docs/visual-basic/programming-guide/concepts/linq/how-to-control-the-type-of-a-projection.md b/docs/visual-basic/programming-guide/concepts/linq/how-to-control-the-type-of-a-projection.md deleted file mode 100644 index 9112abe9c620a..0000000000000 --- a/docs/visual-basic/programming-guide/concepts/linq/how-to-control-the-type-of-a-projection.md +++ /dev/null @@ -1,86 +0,0 @@ ---- -title: "How to: Control the Type of a Projection" -ms.date: 07/20/2015 -ms.assetid: a0171276-0b46-4817-aee5-a8d5191b12fe ---- -# How to: Control the Type of a Projection (Visual Basic) -Projection is the process of taking one set of data, filtering it, changing its shape, and even changing its type. Most query expressions perform projections. Most of the query expressions shown in this section evaluate to of , but you can control the type of the projection to create collections of other types. This topic shows how to do this. - -## Example - The following example defines a new type, `Customer`. The query expression then instantiates new `Customer` objects in the `Select` clause. This causes the type of the query expression to be of `Customer`. - - This example uses the following XML document: [Sample XML File: Customers and Orders (LINQ to XML)](../../../../visual-basic/programming-guide/concepts/linq/sample-xml-file-customers-and-orders-linq-to-xml.md). - -```vb -Public Class Customer - Private customerIDValue As String - Public Property CustomerID() As String - Get - Return customerIDValue - End Get - Set(ByVal value As String) - customerIDValue = value - End Set - End Property - - Private companyNameValue As String - Public Property CompanyName() As String - Get - Return companyNameValue - End Get - Set(ByVal value As String) - companyNameValue = value - End Set - End Property - - Private contactNameValue As String - Public Property ContactName() As String - Get - Return contactNameValue - End Get - Set(ByVal value As String) - contactNameValue = value - End Set - End Property - - Public Sub New(ByVal customerID As String, _ - ByVal companyName As String, _ - ByVal contactName As String) - CustomerIDValue = customerID - CompanyNameValue = companyName - ContactNameValue = contactName - End Sub - - Public Overrides Function ToString() As String - Return String.Format("{0}:{1}:{2}", Me.CustomerID, Me.CompanyName, Me.ContactName) - End Function -End Class - -Sub Main() - Dim custOrd As XElement = XElement.Load("CustomersOrders.xml") - Dim custList As IEnumerable(Of Customer) = _ - From el In custOrd.. _ - Select New Customer( _ - el.@, _ - el..Value, _ - el..Value _ - ) - For Each cust In custList - Console.WriteLine(cust) - Next -End Sub -``` - - This code produces the following output: - -```console -GREAL:Great Lakes Food Market:Howard Snyder -HUNGC:Hungry Coyote Import Store:Yoshi Latimer -LAZYK:Lazy K Kountry Store:John Steel -LETSS:Let's Stop N Shop:Jaime Yorres -``` - -## See also - -- -- [Projections and Transformations (LINQ to XML) (Visual Basic)](../../../../visual-basic/programming-guide/concepts/linq/projections-and-transformations-linq-to-xml.md) diff --git a/docs/visual-basic/programming-guide/concepts/linq/how-to-project-a-new-type-linq-to-xml.md b/docs/visual-basic/programming-guide/concepts/linq/how-to-project-a-new-type-linq-to-xml.md deleted file mode 100644 index e8889da717bd7..0000000000000 --- a/docs/visual-basic/programming-guide/concepts/linq/how-to-project-a-new-type-linq-to-xml.md +++ /dev/null @@ -1,51 +0,0 @@ ---- -title: "How to: Project a New Type (LINQ to XML)" -ms.date: 07/20/2015 -ms.assetid: 8cfb24f5-89b2-4cfb-b85d-e7963f8f1845 ---- -# How to: Project a New Type (LINQ to XML) (Visual Basic) -Other examples in this section have shown queries that return results as of , of `string`, and of `int`. These are common result types, but they are not appropriate for every scenario. In many cases you will want your queries to return an of some other type. - -## Example - This example shows how to instantiate objects in the `Select` clause. The code first defines a new class with a constructor, and then modifies the `Select` statement so that the expression is a new instance of the new class. - - This example uses the following XML document: [Sample XML File: Typical Purchase Order (LINQ to XML)](../../../../visual-basic/programming-guide/concepts/linq/sample-xml-file-typical-purchase-order-linq-to-xml.md). - -```vb -Public Class NameQty - Public name As String - Public qty As Integer - Public Sub New(ByVal n As String, ByVal q As Integer) - name = n - qty = q - End Sub -End Class - -Public Class Program - Shared Sub Main() - Dim po As XElement = XElement.Load("PurchaseOrder.xml") - - Dim nqList As IEnumerable(Of NameQty) = _ - From n In po... _ - Select New NameQty( _ - n..Value, CInt(n..Value)) - - For Each n As NameQty In nqList - Console.WriteLine(n.name & ":" & n.qty) - Next - End Sub -End Class -``` - - This example uses the `M:System.Xml.Linq.XElement.Element` method that was introduced in the topic [How to: Retrieve a Single Child Element (LINQ to XML) (Visual Basic)](../../../../visual-basic/programming-guide/concepts/linq/how-to-retrieve-a-single-child-element-linq-to-xml.md). It also uses casts to retrieve the values of the elements that are returned by the `M:System.Xml.Linq.XElement.Element` method. - - This example produces the following output: - -```console -Lawnmower:1 -Baby Monitor:2 -``` - -## See also - -- [Projections and Transformations (LINQ to XML) (Visual Basic)](../../../../visual-basic/programming-guide/concepts/linq/projections-and-transformations-linq-to-xml.md) diff --git a/docs/visual-basic/programming-guide/concepts/linq/how-to-transform-the-shape-of-an-xml-tree.md b/docs/visual-basic/programming-guide/concepts/linq/how-to-transform-the-shape-of-an-xml-tree.md deleted file mode 100644 index bd1b4da383a03..0000000000000 --- a/docs/visual-basic/programming-guide/concepts/linq/how-to-transform-the-shape-of-an-xml-tree.md +++ /dev/null @@ -1,141 +0,0 @@ ---- -title: "How to: Transform the Shape of an XML Tree" -ms.date: 07/20/2015 -ms.assetid: 84b60854-48b2-452c-87f2-77d53e1d653a ---- -# How to: Transform the Shape of an XML Tree (Visual Basic) -The *shape* of an XML document refers to its element names, attribute names, and the characteristics of its hierarchy. - - Sometimes you will have to change the shape of an XML document. For example, you might have to send an existing XML document to another system that requires different element and attribute names. You could go through the document, deleting and renaming elements as required, but using functional construction results in more readable and maintainable code. For more information about functional construction, see [Functional Construction (LINQ to XML) (Visual Basic)](../../../../visual-basic/programming-guide/concepts/linq/functional-construction-linq-to-xml.md). - - The first example changes the organization of the XML document. It moves complex elements from one location in the tree to another. - - The second example in this topic creates an XML document with a different shape than the source document. It changes the casing of the element names, renames some elements, and leaves some elements from the source tree out of the transformed tree. - -## Example - The following code changes the shape of an XML file using embedded query expressions. - - The source XML document in this example contains a `Customers` element under the `Root` element that contains all customers. It also contains an `Orders` element under the `Root` element that contains all orders. This example creates a new XML tree in which the orders for each customer are contained in an `Orders` element within the `Customer` element. The original document also contains a `CustomerID` element in the `Order` element; this element will be removed from the re-shaped document. - - This example uses the following XML document: [Sample XML File: Customers and Orders (LINQ to XML)](../../../../visual-basic/programming-guide/concepts/linq/sample-xml-file-customers-and-orders-linq-to-xml.md). - -```vb -Dim co As XElement = XElement.Load("CustomersOrders.xml") -Dim newCustOrd = _ - - <%= From cust In co.. _ - Select _ - - <%= cust.Attributes() %> - <%= cust.Elements() %> - - <%= From ord In co.. _ - Where ord..Value = cust.@CustomerID _ - Select _ - - <%= ord.Attributes() %> - <%= ord. %> - <%= ord. %> - <%= ord. %> - <%= ord. %> - _ - %> - - _ - %> - -Console.WriteLine(newCustOrd) -``` - - This code produces the following output: - -```xml - - - Great Lakes Food Market - Howard Snyder - Marketing Manager - (503) 555-7555 - -
2732 Baker Blvd.
- Eugene - OR - 97403 - USA -
- -
- - Hungry Coyote Import Store - Yoshi Latimer - Sales Representative - (503) 555-6874 - (503) 555-2376 - -
City Center Plaza 516 Main St.
- Elgin - OR - 97827 - USA -
- -
-. . . -``` - -## Example - This example renames some elements and converts some attributes to elements. - - The code calls `ConvertAddress`, which returns a list of objects. The argument to the method is a query that determines the `Address` complex element where the `Type` attribute has a value of `"Shipping"`. - - This example uses the following XML document: [Sample XML File: Typical Purchase Order (LINQ to XML)](../../../../visual-basic/programming-guide/concepts/linq/sample-xml-file-typical-purchase-order-linq-to-xml.md). - -```vb -Function ConvertAddress(ByVal add As XElement) As IEnumerable(Of XElement) - Dim fragment = New List(Of XElement) - fragment.Add(<%= add..Value %>) - fragment.Add(<%= add..Value %>) - fragment.Add(<%= add..Value %>) - fragment.Add(<%= add..Value %>) - fragment.Add(<%= add..Value %>) - fragment.Add(<%= add..Value %>) - Return fragment -End Function - -Sub Main() - Dim po As XElement = XElement.Load("PurchaseOrder.xml") - Dim newPo As XElement = _ - - <%= po.@PurchaseOrderNumber %> - <%= CDate(po.@OrderDate) %> - <%= _ - ConvertAddress( _ - (From el In po.
_ - Where el.@Type = "Shipping" _ - Select el) _ - .First() _ - ) _ - %> - - Console.WriteLine(newPo) -End Sub -``` - - This code produces the following output: - -```xml - - 99503 - 1999-10-20T00:00:00 - Ellen Adams - 123 Maple Street - Mill Valley - CA - 10999 - USA - -``` - -## See also - -- [Projections and Transformations (LINQ to XML) (Visual Basic)](../../../../visual-basic/programming-guide/concepts/linq/projections-and-transformations-linq-to-xml.md) diff --git a/docs/visual-basic/programming-guide/concepts/linq/how-to-work-with-dictionaries-using-linq-to-xml.md b/docs/visual-basic/programming-guide/concepts/linq/how-to-work-with-dictionaries-using-linq-to-xml.md deleted file mode 100644 index d07c3fd5bdeaa..0000000000000 --- a/docs/visual-basic/programming-guide/concepts/linq/how-to-work-with-dictionaries-using-linq-to-xml.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -title: "How to: Work with Dictionaries Using LINQ to XML" -ms.date: 07/20/2015 -ms.assetid: 6cb3f969-1986-414a-b850-87418712edea ---- -# How to: Work with Dictionaries Using LINQ to XML (Visual Basic) -It is often convenient to convert varieties of data structures to XML, and XML back to other data structures. This topic shows a specific implementation of this general approach by converting a to XML and back. - -## Example - This example uses XML literals and a query in an embedded expression. The query projects new objects, which then become the new content for the `Root` object. - -```vb -Dim dict As Dictionary(Of String, String) = New Dictionary(Of String, String)() -dict.Add("Child1", "Value1") -dict.Add("Child2", "Value2") -dict.Add("Child3", "Value3") -dict.Add("Child4", "Value4") -Dim root As XElement = _ - - <%= From keyValue In dict _ - Select New XElement(keyValue.Key, keyValue.Value) %> - -Console.WriteLine(root) -``` - - This code produces the following output: - -```xml - - Value1 - Value2 - Value3 - Value4 - -``` - -## Example - The following code creates a dictionary from XML. - -```vb -Dim root As XElement = _ - - Value1 - Value2 - Value3 - Value4 - - -Dim dict As Dictionary(Of String, String) = New Dictionary(Of String, String) -For Each el As XElement In root.Elements - dict.Add(el.Name.LocalName, el.Value) -Next -For Each str As String In dict.Keys - Console.WriteLine("{0}:{1}", str, dict(str)) -Next -``` - - This code produces the following output: - -```console -Child1:Value1 -Child2:Value2 -Child3:Value3 -Child4:Value4 -``` - -## See also - -- [Projections and Transformations (LINQ to XML) (Visual Basic)](../../../../visual-basic/programming-guide/concepts/linq/projections-and-transformations-linq-to-xml.md)