Read xml data using Linq

Binumon George 161 Reputation points
2022-09-28T14:52:03.533+00:00

Hi All,
In my application I am reading xml file to draw image. Here i want to get lowest x and y values from flies using LINQ. I want to avoid loop to get better performance

Below is my code to read from xml

XDocument xdoc = XDocument.Load("c:\Xml\BI-Parent WF.xml");

            var drawingXML = from rec in xdoc.Descendants("figures").Descendants("figure")  
                               select new  
                               {  
                                   xImageValue = rec.Attribute("x"),  
                                   yImageValue = rec.Attribute("y"),  
                                   type = rec.Attribute("type")  
                               };  

I tried below code to get lowest x value from drawingXML

var minX=     (from rec in drawingXML select  rec.xImageValue).Min();   

But getting below error on runtime

At least one object must implement IComparable.

So anyone help me to get lowest value of x using linq?

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,204 questions
.NET Runtime
.NET Runtime
.NET: Microsoft Technologies based on the .NET software framework.Runtime: An environment required to run apps that aren't compiled to machine language.
1,117 questions
0 comments No comments
{count} votes

Accepted answer
  1. HugeZhong 106 Reputation points
    2022-09-29T01:21:01.827+00:00
    var xdoc = XDocument.Load(@"C:\Users\10235\Desktop\xlinq\1.xml");  
      
                var xml = from node in xdoc.Descendants("figure")  
                          select new  
                          {  
                              x = int.Parse(node.Attribute("x").Value),  
                              y = int.Parse(node.Attribute("y").Value),  
                              type = node.Attribute("type").Value  
                          };  
      
                var minX = (from item in xml select item.x).Min();  
                var minY = (from item in xml select item.y).Min();  
      
                Console.WriteLine("minX={0} minY={1}", minX,minY);  
    

    This works. xAttribute do not implement IComparable inerface,so you cannot campare them. Instead you can convert x and y value to int.

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. HugeZhong 106 Reputation points
    2022-09-28T15:16:06.323+00:00

    I'm not very sure, but can you try the below code first:
    var drawingXML = from rec in xdoc.Descendants("figures").Descendants("figure")
    select new
    {
    xImageValue = Int.Parse(rec.Attribute("x")),
    yImageValue = Int.Parse(rec.Attribute("y")),
    type = rec.Attribute("type")
    };