c#循环遍历datatable中的不同值

时间:2012-03-19 23:56:26

标签: c# .net winforms linq

我有一个数据表:

+----------+--------+
| Rep Name | Volume |
+----------+--------+
| Alex     |      9 |
| Alex     |      1 |
| Alex     |      3 |
| Liza     |     24 |
| Liza     |     17 |
| Pam      |      0 |
| Pam      |      6 |
+----------+--------+

我正在为REP NAME

中的每个独特人发送一封电子邮件

示例:

Hi Alex, Today your volume was 9, and 1, and 3.

下一封电子邮件:

Hi Liza, Today your valume was 24, and 17.

我想知道在REPNAME

的唯一值上循环数据表的最简单方法

类似的东西:

 var DistinctList = datatable123.Select(x=> x.repname).Distinct();

然后我会循环通过DistinctList?

1 个答案:

答案 0 :(得分:4)

您应该使用GroupBy执行此任务。

更新:我已重写代码,现在您可以将其与DataTable一起使用。

var list = from x in datatable123.AsEnumerable()
           group x by (string) x["repname"] into g
           select g;

foreach (var x in list)
{
   Console.WriteLine("Hi {0}, Today your volume was {1}.", x.Key,
      String.Join(", and ", x.Select(p => p["volume"])));
}