Tuesday, May 18, 2010

Handy Linq/DataSet operations

Create a list from a field in the DataSet: (Query syntax)

List<uint> myList = (from row in aDataSet.Tables[0].AsEnumerable()
                     select row.Field<uint>("AColumnName")).ToList();

or: (Method Syntax)

List<uint> myList = aDataSet.Tables[0].AsEnumerable().Select(dataRow => dataRow.Field<uint>("AColumnName")).ToList();

or more generically...

IEnumerable<uint> myList = aDataSet.Tables[0].AsEnumerable().Select(dataRow => dataRow.Field<uint>("AColumnName"));



Create a Dictionary from two fields in the DataSet:

Dictionary<uint, uint> myDictionary = aDataSet.Tables[0].AsEnumerable()
    .ToDictionary(k => k.Field<uint>("KeyColumn"), v => v.Field<uint>("ValueColumn"));