Converting xml to custom class using lambda linq

Trying to parse an XML document into a custom class that I created. I have successfully figured out how to parse a document, but for some reason I need to do this in IEnumerable

one instance of my custom class instead. It is much easier to just show the code than to explain it in detail, so see the code snippets below.

Working code

IEnumerable<Ping> ping = xmlDoc.Descendants("PING_SEND").Select(p => new Ping
    {
        TRAN_ID = (string)p.Element("TRAN_ID"),
        MILOC = (string)p.Element("MILOC"),
        TRANDATE = (string)p.Element("TRANDATE"),
        TRANTIME = (string)p.Element("TRANTIME"),
        COUNTRY = (string)p.Element("COUNTRY")
    });

      

What results should be used ...

foreach (Ping p in ping)
{
    cmd.Parameters.AddWithValue("@TRAN_ID", p.TRAN_ID);
    cmd.Parameters.AddWithValue("@MILOC", p.MILOC);
    cmd.Parameters.AddWithValue("@SITE_REF", "");
}

      

... when adding parameters to insert into the database. What I have tried (and needed) is what would be more in the spirit of this ...

Idea of ​​the desired code

Ping ping =(Ping)xmlDoc.Descendants("PING_SEND").Select(p => new Ping
    {
        TRAN_ID = (string)p.Element("TRAN_ID"),
        MILOC = (string)p.Element("MILOC"),
        TRANDATE = (string)p.Element("TRANDATE"),
        TRANTIME = (string)p.Element("TRANTIME"),
        COUNTRY = (string)p.Element("COUNTRY")
    });

//... Other operations and database functions...

cmd.Parameters.AddWithValue("@TRAN_ID", ping.TRAN_ID);
cmd.Parameters.AddWithValue("@MILOC", ping.MILOC);
cmd.Parameters.AddWithValue("@SITE_REF", "");

      

+3


source to share


1 answer


It looks like all you need is a call First()

or Single()

or whatever - to say that you only need one result (first or only result - other options are available):

Ping ping = xmlDoc.Descendants("PING_SEND").Select(...).First();

      

Basically the problem is that after Descendants(...).Select(...)

you have a sequence of links Ping

when you only want it.



If in fact there may be multiple elements PING_SEND

- or not - you really need to think about what you want to do in this situation. LINQ provides various methods to help you depending on your requirements:

  • First

  • Single

  • Last

  • FirstOrDefault

  • SingleOrDefault

  • LastOrDefault

Methods OrDefault

allow you to handle the case when there are no results.

+5


source







All Articles