Skip to content

Instantly share code, notes, and snippets.

@jinan-kordab
Created January 22, 2019 15:14
Show Gist options
  • Save jinan-kordab/d4a88ee6b49148aee756e9df679f9044 to your computer and use it in GitHub Desktop.
Save jinan-kordab/d4a88ee6b49148aee756e9df679f9044 to your computer and use it in GitHub Desktop.
Grouping DataTable raw records with LINQ
var DistinctGroupedColumns = dt.AsEnumerable().GroupBy(x => x.Field<Int32>("COLUMNONE")).Distinct().ToList();
foreach (var date in DistinctGroupedColumns)
{
//For each distinct record, get the associated list of records
var associatedListOfRecords = (from alofrec in dt.AsEnumerable() where alofrec.Field<Int32>("COLUMNONE").Date.ToString() == date.Key.ToString()
select alofrec).ToList();
int i = 0;
//The foreach below gets associated records per grouped group.
foreach (var timePart in associatedListOfRecords)
{
var COLUMNONE = Convert.ToDateTime(timePart.Field<DateTime>("CDateTime")).Date.ToString("dd/mm/yyyy");
var COLUMNTWO = Convert.ToDateTime(timePart.Field<DateTime>("CDateTime")).ToString("HH:mm");
var COLUMNTHREE = timePart.Field<String>("PhoneNumber").ToString();
var COLUMNFOUR = timePart.Field<String>("AccountNumber").ToString();
var COLUMNFIVE = timePart.Field<String>("HouseNumber").ToString();
// Do something with the column values, like print an HTML grid in Razor View, or send an SMTP email with those values.
// i is an additional variable, just in case, to keep record count for each group
i = i + 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment