tags:

views:

38

answers:

4

The xml file is having the following structure

<Root>
    <Child value="A"/>
    <Child value="B"/>
    <Child value="C"/>
    <Child value="D"/>
     <Child value="E"/>
</Root>

and the dictonary

     Dictionary<int, string> dict = new Dictionary<int, string>();

i need to read the attribute value of "value" from the file and add the same to the dictonary as value and index as key

like

    dict[1]="A"
    dict[2]="B"
    dict[3]="C"
    dict[4]="D"
    dict[5]="E"

for this i'm using the XML to LINQ query as

    dict = XDOC.Load(Application.StartupPath + "\\Test.xml"). 
                Descendants("Child").ToDictionary("????", x => x.Attribute("Value").Value);

wat i have to use in the place of "????" in the query

please give a solution to do this

A: 

If you need access to the index of an element in a sequence, you can use the overload of Enumerable.Select that takes a Func<TSource, int, TResult>.

dict = XDOC.Load(Application.StartupPath + "\\Test.xml")
    .Descendants("Child")
    .Select((element, index) => 
        new { index, value = element.Attribute("Value").Value })
    .ToDictionary(x => x.index, x => x.value);
Quartermeister
A: 

I assume you don't actually want them all to have the same key, but rather an index value indicating their position in the original set:

        var dict = xDoc.Descendants("Child")
            .Select((xe, i) => new { Index = i, Element = xe })
            .ToDictionary(a => a.Index, a => a.Element.Attribute("value").Value);
Toby
+1  A: 

You're immediate problem is that you can't have two entries in the dictionary with the same keys, I'm assuming you'll want some sort of identifier....

int i = 0;
var dic = XDOC.Load(...)
  .Root
  .Descendants("Child")
  .ToDictionary(el => (i++), el => el.Attribute("value").Value);

But then, if its just a sequential collection, why not just use a list:

var list = XDOC.Load(...)
  .Root
  .Descendants("Child")
  .Select(el => el.Attribute("value").Value)
  .ToList();

Edit: I didn't know about the element index part, good call peoples!

Matthew Abbott
+1 for the simplicity of the ToList()
Toby
The Select overload is way to go. Not too keen on Linq with side effects. The list idea is pretty astute though :)
spender
+1  A: 
dict = XDOC
    .Load(Application.StartupPath + "\\Test.xml")
    .Descendants("Child")
    .Select((x,i) => new {data=x, index=i})
    .ToDictionary(x => x.index, x => x.data.Attribute("Value").Value);
spender