How can I organize two objects in order to be able to join them by key?

So basically, I read in two XML documents. The first has two values ​​that must be saved: name and value. The second has four meanings: Name, DefaultValue, Type and Limit. When reading in documents, I want to store them in some object. I should be able to then combine the two objects into one, which stores 5 values. XML documents vary in length, but the second will always be on top compared to the first.

Example:

<XML1> <Item1> <Name>Cust_No</Name> <Value>10001</Value> </Item1> <Item4> ITEM4 NAME AND VALUE </Item4> <Item7> ITEM 7 NAME AND VALUE </Item7> </XML1> <XML2> <Item1> <Name>Cust_No</Name> <DefaultValue></DefaultValue> <Type>varchar</Type> <Limit>15</Limit> </Item1> 6 MORE TIMES ITEMS 2-7 </XML2> 

I already have a code loop through XML. I really need thoughts on how best to store data. Ultimately, I want to be able to join two objects in Key Name. I tried string[] and arrayList[] , but I ran into difficulties combining them. I also read in Dictionary , but also could not implement this (I have never used Dictionary before).

+4
source share
1 answer

Here is a Linq to Xml query that will combine the two XDocuments and highlight anonymous objects for related elements. Each object will have five properties:

 var query = from i1 in xdoc1.Root.Elements() join i2 in xdoc2.Root.Elements() on (string)i1.Element("Name") equals (string)i2.Element("Name") into g let j = g.SingleOrDefault() // get joined element from second file, if any select new { Name = g.Key, Value = (int)i1.Element("Value"), DefaultValue = (j == null) ? null : (string)j.Element("DefaultValue"), Type = (j == null) ? null : (string)j.Element("Type"), Limit = (j == null) ? null : (string)j.Element("Limit") }; 

XDocuments are created as follows:

 var xdoc1 = XDocument.Load(path_to_xml1); var xdoc2 = XDocument.Load(path_to_xml2); 

Using request:

 foreach(var item in query) { // use string item.Name // integer item.Value // string item.DefaultValue // string item.Type // string item.Limit } 
+2
source

All Articles