How to store duplicate data from xml file in C#
I'm having an xml file like
<Root>
<Child val1="1" Val2="0"/>
<Child val1="1" Val2="2"/>
<Child val1="1" Val2="3"/>
<Child val1="1" Val2="4"/>
<Child val1="1" Val2="5"/>
<Child val1="6" Val2="0"/>
<Child val1="7" Val2="0"/>
</Root>
i need to store the data in any temporary storage ( namely a Dictionary
) for som开发者_如何学Pythone sort of manipulations . but i cannot use dictionary
here because dictionary does not support same keys. can any one suggest me a better way to store this data?
Well, you could use a Dictionary<int, List<int>>
- or for storage only (no changes) you could use LINQ's ToLookup
method which will build a multi-valued map for you very easily. Something like (using LINQ to XML):
var lookup = doc.Descendants("Child")
.ToLookup(x => (int) x.Attribute("val1"),
x => (int) x.Attribute("val2"));
// Will iterate 5 times, printing 0, 2, 3, 4, 5
foreach (var value in lookup[1])
{
Console.WriteLine(value);
}
EDIT: To display all the information, you'd do something like:
foreach (var grouping in lookup)
{
foreach (var value in grouping)
{
Console.WriteLine("{0} {1}", grouping.Key, value);
}
}
If .NET 4.0 you can use a Tuple<int, int> and List<Tuple<int, int>> if data is not key-value pairs
you can still use a dictionary for the val1 values, just have the second value be a list of values instead of just a list. then simply check if the DataKey exists, if it does do a list.Add(val2)
精彩评论