Reputation: 77
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
Upvotes: 1
Views: 156
Reputation: 1503869
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.
Upvotes: 3
Reputation: 7352
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();
Upvotes: 2