简体   繁体   中英

How to combine 2 LINQ XML queries in C#

noob here using LINQ. I have created 2 queries that I would like combining if possible.

        var myData =
        from el in root.Descendants().Elements("sensor")
        where (string)el.Attribute("name") == "Sensor1"
        select el;

        var myData2 =
        from el in myData.Elements("evt")
        select new
        {
            t1 = el.Attribute("time").Value,
            v1 = el.Attribute("val").Value
        };  

        dataGridView1.DataSource = myData2.ToList();

Ideally I'd like to know how to combine the 2 queries.

Thanks

It is posible, you could do this.

var result = root.Descendants()
    .Elements("sensor")
    .Where(el=>(string)el.Attribute("name") == "Sensor1")
    .Elements("evt")
    .Select(el=> new
        {
            t1 = el.Attribute("time").Value,
            v1 = el.Attribute("val").Value
        })
     .ToList()
dataGridView1.DataSource = result;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM