1

I've the below XML:

<?xml version="1.0" standalone="yes"?>
<TestSuite>
  <TestCase Name="XXX" ID="123;234; 345; 456">
    <CodeBlock />
  </TestCase>
  <TestCase Name="East" ID="11,22,33, 44, 55">
    <CodeBlock />
  </TestCase>
</TestSuite>         

I need to get all the ID and order them by ID ASC, below is my Linq:

var r = (from lv1 in xdoc.Descendants("TestCase")
         select new { ID = lv1.Attribute("ID").Value })
        .Where(d => d.ID != string.Empty)
        .GroupBy(l => l.ID)
        .ToList();

I now get:

123;234; 345; 456
11,22,33, 44, 55

But how can I get the IDs like:

11
22
33
44
55
123
234
345
456
3
  • Is ID Int type or string type ?? Commented Apr 22, 2014 at 6:04
  • string type, since some ID may be string Commented Apr 22, 2014 at 6:06
  • It is very accurate that you have included the xml of yours. Commented Apr 22, 2014 at 6:13

2 Answers 2

3

It's not clear why you're grouping at all... and you just need to split the values and flatten that with SelectMany, by the looks of it:

var separators = new[] { ';', ',' };
var r = xdoc.Descendants("TestCase")
            .Select(x => (string) x.Attribute("ID"))
            .Where(ids => ids != null)
            .SelectMany(ids => ids.Split(separators,
                                         StringSplitOptions.RemoveEmptyEntries))
            .Select(id => int.Parse(id.Trim()))
            .OrderBy(id => id)
            .ToList();

Note that I've parsed each ID as integer, on the grounds that if you treat them just as strings, then "123" comes before "55". If they're actually not necessarily integers, but you want to sort any values which can be parsed as integers that way, then the ordering part becomes trickier.

Sign up to request clarification or add additional context in comments.

Comments

2

This might work:

var r = (from lv1 in xdoc.Descendants("TestCase")
        select new { ID = lv1.Attribute("ID").Value }).
        Where(d => d.ID != string.Empty).OrderBy(l => int.Parse(l.ID)).ToList();

4 Comments

Input string was not in a correct format, "123;234; 345; 456"
that's the right idea.. now just change the last OrderBy(l => int.Prase(l.ID.ToString().Replace(";", ""))) ... +1
I'm puzzled, l.ID.ToString().Replace(";", "") returns string,how can it be parsed to int?
Yes it will return string without the semi colon. That can be parsed into integer

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.