使用linq计算DataTable中每个列值的出现

calculating the occurrence of each column values in DataTable using linq

我有一个数据 table,其中包含一组属性,例如(天气、风等)

我想计算每个列或属性中每个值的出现次数。

这是我的数据表:

输出将类似于:

Weather:
   sunny : 120

   cloudy : 200

   rainy : 300
Wind:
   slight : 200

   strong : 120

我不知道从哪里开始,任何想法都可以挽救我的一天

谢谢

这很容易。

这将创建一组具有属性 KeyCount

的匿名对象
// Add to the project a reference to System.Data.DataSetExtensions.dll
// Add a "using System.Data" to the cs file

// dt is your DataTable

var res = (from x in dt.AsEnumerable()
           group x by (string)x["Weather"] into y
           select new { Key = y.Key, Count = y.Count() }).ToArray();

这将创建一个包含相同数据的 Tuple<string, int> 数组。

var res2 = (from x in dt.AsEnumerable()
            group x by (string)x["Weather"] into y
            select Tuple.Create(y.Key, y.Count())).ToArray();

记得看评论!

很明显,您必须为每一列重复所有内容。