What’s the most elegant way to collapse duplicate columns from tabular data into lists?
Example: I wrote an SQL query which returns rows which include duplicate data except for a single differentiating column:
FIRST LAST AGE CAR
Charles Burns 32 Accord
Charles Burns 32 Buick
Charles Burns 32 Lexus
Anders Hejlsberg 51 Porsche
Anders Hejlsberg 51 Ferrari
Anders Hejlsberg 51 Bugatti
Anders Hejlsberg 51 Pinto
I read these using something like the following, then put them into a CarInfo object:
while(reader.Read()) {
first = reader["first"]
last = reader["last"]
//...
}
var myData = new CarInfo(first, last, ...);
The object looks like:
// CarInfo: Need 7 total instances with example data
string first { get; private set; }
string last { get; private set; }
int age { get; private set; }
string car { get; private set; }
I’d like it to look like:
// CarInfo: Need only 2 instances with example data;
string first { get; private set; }
string last { get; private set; }
int age { get; private set; }
List<string> cars { get; private set; }
I can of course do this manually, for example by picking columns that form a unique ID and checking if they are already in my List (or dictionary or whatever), but that seems really laborious.
I’m just familiar enough with LINQ to suspect it can beautifully collapse this data, but not quite familiar enough for an exact method to come to mind.
You can load a
DataTableand use LINQ-To-DataSet:Above groups by an anonymous type with three fields as key. Then the
CarInfoinstances are initialized with these fields and aList<String>property with all cars per group.