I have a datatable which was returned from database.
the content is similar below:
UserId | Address | Phone
1 blah 0123
1 blah2 3445
2 sdsdf 2343
2 ssf 2223
3 sadss 2321
This is the content of DataTable which is returned from database.
Now I just would like to group the results by User Id and loop through to out put result
foreach (DataRow userRow in DataTableGroupedByUser){
foreach (DataRow restOfColumns in AddressAndPhoneRows){
Output user details } }
The output I would get should be:
User Id: 1
Address Phone
1- blah 0123
2- blah2 3445
User Id 2:
Address Phone
1- sdsdf 2343
2- ssf 2223
user Id :3 ...
I hope you get the idea.
Basically I do not want to query the database many times for each user but just use one query to pull all data and handle the grouping in the memory.
There are also other reason for this.
Is there any way to achieve this by using DataTable and filtering?
You can use LINQ:
var groupedByUserId = table.AsEnumerable().GroupBy(row => row.Field<int>("UserId"));
foreach(var group in groupedByUserId)
{
Console.WriteLine("User Id: {0}", group.Key);
Console.WriteLine("Address Phone");
int rowNum = 0;
foreach(DataRow row in group)
{
Console.WriteLine("{0}- {1} {2}", ++rowNum, row.Field<string>("Address"), row.Field<string>("Address"));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With