tags:

views:

41

answers:

4

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 some 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?

A: 

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)

Mauro
+2  A: 

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);
    }
}
Jon Skeet
@Pramodh: I've edited my answer to give an example.
Jon Skeet
@ Jon Skeet : How do i get the value of val2(4th element where `val1` value is `1` and `val2` value is `4`) if i use LookUp . Can u please explain with sample code –
Pramodh
@ Jon Skeet : i need to display the data from the temporary storage to a list view(contains two columns) if i'm using `dictionary` i can iterate through it and can display it in the listview. but in case of `lookup` how do i do this. the list view will be like `1 0` `1 --- 2` `1 --- 3` `1 --- 4` `1 --- 5` `6 --- 0` `7 --- 0`. can you please explain this too
Pramodh
@Pramodh: Well, I've added a bit more information - but it's not clear whether that's exactly what you'll want.
Jon Skeet
+1  A: 

If .NET 4.0 you can use a Tuple<int, int> and List<Tuple<int, int>> if data is not key-value pairs

veggerby
A: 

In this case you can just create a struct Child with two fields val1 and val2. Then you can use a List of Child to store this data.
If you need some sorting or equality issues or your xml is more complex than example you might need to use Dictionary or HashTable of Lists.

MAKKAM