1

I am totally out of Ideas and my C# / LINQ / XML skills are stills very weak. Maybe someone can help me with a relatively simple task that I don't want to write a whole programm around:

I need to get the Highest Customer-ID in an XML Database that looks somewhat like this:

<xml>
  <customers>
    <customer>
      <customerid>a00001</customerid>
      <name>this</name>
    </customer>
    <customer>
      <customerid>a00031</customerid>
      <name>that</name>
    </customer>

and so on...

What I have tried so far is a mixture of code I have used for other linq/xml that actually worked, combined with stuff I found here:

var readme = XElement.Load("someXML");
int tempHigh;
var highIDs =
    (from va in readme.Elements("customers").Elements("customer")
     where Convert.ToInt32(va.Element("customerid").Value.Substring(2, 5)) > tempHigh
     select Convert.ToInt32(va.Element("customerid").Value.Substring(2,5)));

tempHigh = Convert.ToInt32(highIDs.Element("customerid").Value);

return tempHigh;

And something is not working. Anyone have an idea where I don't have to put all the data in an array, sort that array and give out the first element (because that is my only Idea left but seems a bit too much)

1

2 Answers 2

5
int highestId = readme
    .Elements("customers")
    .Elements("customer")
    .Select(cust => Convert.ToInt32(cust.Element("customerid").Value.Substring(1))
    .Max();
Sign up to request clarification or add additional context in comments.

2 Comments

in this case .Substring(2) would be better since the customerid might get more digits as the number of customers grows.
why you start from 2 shouldn't it be 1 ?
0

or more concise using a combination of linq/xpath

int id = readme.XPathSelectElements("/customers/customer/customerid").Max(cid => int.Parse(cid.Value.Substring(1)));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.