Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add data to a dictonary in c#

How to add data to dictonary from xml file

scenerio:

I've declared a dictonary like

 Dictonary<string,string> SampleDict=new Dictonary<string,string>();

and my xml file is like

 <Data>
   <Element ValOne="1" ValTwo="0" />
   <Element ValOne="2" ValTwo="2" />
   <Element ValOne="3" ValTwo="4" />
   <Element ValOne="4" ValTwo="6" />
   <Element ValOne="5" ValTwo="8" />
   <Element ValOne="6" ValTwo="10" />
   <Element ValOne="7" ValTwo="12" />
   <Element ValOne="8" ValTwo="14" />
   <Element ValOne="9" ValTwo="16" />
   <Element ValOne="10" ValTwo="18" />
</Data>

i need to read the value of "ValOne" and "ValTwo" using LINQ and insert the same into the above declared dictonary

and how to add the contents of the dictonary to a listview which contains two columns.

Please help me to do this

Thanks in advance

like image 660
Thorin Oakenshield Avatar asked Dec 18 '22 00:12

Thorin Oakenshield


2 Answers

You can use Linq to XML and ToDictionary for this.

var doc = XDocument.Load("path to xml");
doc.Elements("Element").ToDictionary(
  elem => elem.Attribute("ValOne").Value, //Dictionary key
  elem => elem.Attribute("ValTwo").Value  //Dictionary value
);

This particular overload of ToDictionary uses different lambdas to extract keys and values for the generated collection.

like image 179
Igor Zevaka Avatar answered Dec 24 '22 02:12

Igor Zevaka


Presumably you want ValOne to be the key and ValTwo to be the value?

document.Descendants("Element")
    .ToList()
    .ForEach(e => SampleDict[e.Attribute("ValOne").Value] = e.Attribute("ValTwo").Value);

This assumes you have read your XML file into an XDocument or XElement

like image 20
jeffora Avatar answered Dec 24 '22 00:12

jeffora