I have a sql query that I return into a DataTable:
SELECT TABLE_NAME, COLUMN_NAME, DATA_TYPE, DATA_LENGTH
FROM USER_TAB_COLUMNS
WHERE TABLE_NAME IN (SELECT DBTABLE FROM MY_APP_SETTINGS)
With this, I want to create a Dictionary<string, List<ColumnInfo>>, where the key is TABLE_NAME and ColumnInfo is a custom class with properties to match the other three fields returned in the query. So, far I have:
IEnumerable<DataRow> rows = MyDataTable.Rows.Cast<DataRow>();
var ExistingColumns = MyDataTable.AsEnumerable().Select(dataRow => rows
.Select(row => new {
Key = row["TABLE_NAME"],
Value = new ColumnInfo(){
ColumnName = row["COLUMN_NAME"].ToString(),
DataType = row["DATA_TYPE"].ToString(),
DataLength = int.Parse(row["DATA_LENGTH"].ToString())
}
}).ToDictionary(data => data.Key, data => data.Value));
However, this has two problems: 1) There are duplicate keys, and 2) the Value is just a single instance of the class, not a collection.
How can I acheive this conversion using linq?
Thanks!
First, use a
GroupByin order to group the rows by table name. This ensures that the table names will be unique.The first argument to group by selects the key, the second argument the value. Then it is easy to create the dictionary. The grouping
gis anIEnumerable<ColumnInfo>. So the list can simply be created withg.ToList().