Вот несколько способов сделать это в памяти с помощью LINQ.
List<SomeClass> source = new List<SomeClass>()
{
new SomeClass(){ theID = 1, theGroup = 2, theValue="Red"},
new SomeClass(){ theID = 2, theGroup = 2, theValue="Blue"},
new SomeClass(){ theID = 3, theGroup = 2, theValue="Green"},
new SomeClass(){ theID = 1, theGroup = 3, theValue=10},
new SomeClass(){ theID = 2, theGroup = 3, theValue=24},
new SomeClass(){ theID = 3, theGroup = 3, theValue=30},
new SomeClass(){ theID = 1, theGroup = 4, theValue=1},
new SomeClass(){ theID = 2, theGroup = 4, theValue=2},
new SomeClass(){ theID = 3, theGroup = 4, theValue=3}
};
//hierarchical structure
var result1 = source.GroupBy(item => item.theID)
.Select(g => new {
theID = g.Key,
theValues = g
.OrderBy(item => item.theGroup)
.Select(item => item.theValue)
.ToList()
}).ToList();
//holds some names for the next step.
Dictionary<int, string> attributeNames = new Dictionary<int,string>();
attributeNames.Add(2, "CHOICE");
attributeNames.Add(3, "COUNT");
attributeNames.Add(4, "SORT");
//xml structure
var result2 = source
.GroupBy(item => item.theID)
.Select(g => new XElement("Row",
new XAttribute("ID", g.Key),
g.Select(item => new XAttribute(attributeNames[item.theGroup], item.theValue))
));