1

I have a datatable which is holding two columns as 'Name' and 'Value'.

I have xml also which looks like below so I need to join datatable column with XML attribute then select XML Value if attribute value are present in datatable column. I have tried many possible ways but none of them helped . Please help me how to achieve this with help of linq!

Below is XML code

<Serverlist>
    <server name='Eric' value='9' />
    <server name='Donot' value='92' />
</Serverlist>

Below is code snippet which I have used

XElement xelement = XElement.Load("path");

var data = from dtt in dt.AsEnumerable()
           join xele in xelement.Descendants("server")
           on (string)dtt.Field<string>("Name") equals (string)xele.Attribute("name")
           select new { name =(String) xele.Attribute("name"), value=(string) xele.Attribute("value")};

foreach(var v in data) 
{
    Console.WriteLine(v);
}
Shoaib Iqbal
  • 1,208
  • 11
  • 21
Akhilesh
  • 171
  • 2
  • 20
  • What is the current input? What is the current output? And what is the expected output? – Yacoub Massad May 26 '16 at 09:12
  • current inputs are attached xml and datatable with two column 'Name and Value and value are same as xml attribute value so according to that it should retrieve some value in data but current output is null. – Akhilesh May 26 '16 at 09:18
  • There is nothing wrong with your code. I've tried it and it works. Maybe the problem is with the data in the data table. Can you show how you populate the data table? – Yacoub Massad May 26 '16 at 09:26
  • For testing purpose I just used below simple code to create data table DataTable dt=new DataTable(); dt.Columns.Add("Name"); dt.Columns.Add("Value"); DataRow dr = dt.NewRow(); dr["Name"] = "Eric"; dr["Value"] = 9; dt.Rows.Add(dr); DataRow dr1 = dt.NewRow(); dr1["Name"] = "KI"; dr1["Value"] = 9; dt.Rows.Add(dr1); – Akhilesh May 26 '16 at 09:28
  • Often these issue have to do with XML namespace. Independently attempt to enumerate xml and datatable with code and see which is wrong. You don't need the (String) in front of the dtt.Field because the angle brackets are already doing the cast. – jdweng May 26 '16 at 09:31
  • 1
    Your code is working and it is giving me `{ name = Eric, value = 9 }` – Yacoub Massad May 26 '16 at 09:35
  • Yes Yacoub thanks for your quick response as now i converted to string hence it started working thanks! – Akhilesh May 26 '16 at 09:39

1 Answers1

0

I think you are trying to merge as opposed to join?

Convert them both to Dictionaries (the database list and the xml document). Then merge the two dictionaries together. Good examples are in this thread. for example:

dictionaryFrom.ToList().ForEach(x => dictionaryTo.Add(x.Key, x.Value));
Simple and easy. According to this blog post it's even faster than most loops.
Community
  • 1
  • 1
Murray Foxcroft
  • 12,785
  • 7
  • 58
  • 86