Linq to XML question

Bigbacon

Fully [H]
Joined
Jul 12, 2007
Messages
21,344
Trying to turn a linq result set into XML and I am having trouble with one bit.

I have a dump of some data, without trying to put all of it, lets just say it is 4 columns per row

ex.
UNITTITLE | PersonsName | ClassID | Score

what I was trying to do is transform that result set into XML so I can slap an XSLT on it and be done with it OR use the XML for something else (like creating an XLSX file)

Problem I ran into is trying to just get a distinct list of the UNITTITLE to use as an aatribute for a parent node in the XML or just as a sub node of the parent.

so, if I sub query the result set first to get just the distinct UNITTITLEs, it works fine.

Code:
Dim units = (From r In _reportData Select r.unitTitle).Distinct

            xml.Element("Results").Add(New XElement("Units", _
                                                        From r In units _
                                                        Select New XElement("Unit", r) _
                                                    ) _
                                                )

if I try something similar without the subquery result set, it doesn't seem to do the Distinct part. so if there are 5 rows and 2 distinct UNITTITLEsI end up with 5 UNIT nodes.

Code:
 xml.Element("Results").Add(New XElement("Units", _
                                                        (From r In _reportData _
                                                        Select New XElement("Unit", r.unitTitle)).Distinct() _
                                                    ) _
                                                )

I assume I am missing something really stupid but I don't know what.
 
.Distinct returns IEnumerable, which I think is your problem here. I believe the function you're looking for is .First (or .FirstOrDefault if you're not a purist).
 
let me try that.

the problem with First is it only get the first result. I need to get all the distinct results.
 
Last edited:
Distinct performs the equality operator on the entire row, not the first column.

There's nothing wrong with subqueries.
 
Sounds like you want to group the results by unitTitle?

Code:
var units = new XElement("Results", _reportData.GroupBy(x => x.unitTitle)
		.Select(x => new XElement("Unit", new XAttribute("unitTitle", title.Key), new XElement("stuff". x.Value.Select(...)));

I'm just making this up, it might not be what you're looking for...
 
Last edited:
Back
Top