[英]How do I count the number of times an item appears in a column in a datatable in c#
I have created a datatable with two columns, "Function" and "Date". 我创建了一个包含两列的数据表:“函数”和“日期”。 This table records the date that each of n functions is used on a website. 该表记录了网站上n个功能中每个功能使用的日期。 I want to extract the number of times that a particular function such as "Access" appears in the table. 我想提取特定功能(例如“访问”)出现在表中的次数。 Any help will be appreciated. 任何帮助将不胜感激。
DataTable table = new DataTable();
table.Columns.Add("Function", typeof(string));
table.Columns.Add("Date", typeof(datetime));
table.Rows.Add(Access, 01/08/2012);
table.Rows.Add(Load, 01/08/2012);
table.Rows.Add(Save, 01/08/2012);
table.Rows.Add(Access, 02/08/2012);
table.Rows.Add(Print, 02/08/2012);
int accessCount = 0;
foreach (DataRow row in table.Rows)
{
if (row["Function"] == "Access")
{
accessCount++;
}
}
var results = table.AsEnumerable()
.GroupBy(row => row.Field<string>("Function"))
.Select(group => new
{
Function = group.Key,
Count = group.Count(),
});
You can use linq for it 您可以使用linq
var result = from rec in table.AsEnumerable
group rec by rec.Field<string>("Function") into g
select new { Function = g.Key, Count = g.Count()}
You can use Linq-To-Datatable
and Enumerable.GroupBy
to group by your function. 您可以使用Linq-To-Datatable
和Enumerable.GroupBy
对功能进行分组。 Then you can use ToDictionary
to build a dictionary with the function as key and the count as value: 然后,您可以使用ToDictionary
构建以功能为键,计数为值的字典:
var functionLookup = table.AsEnumerable()
.GroupBy(r => r.Field<string>("Function"))
.ToDictionary(g => g.Key, g => g.Count());
int accessCount = functionLookup["Access"]; // 2
Note that it's case sensitive by default. 请注意,默认情况下区分大小写。 If you want it to be case insensitive you would need to pass the appropriate IEqualityComparer
for the key, in this case: 如果希望它不区分大小写,则需要为密钥传递适当的IEqualityComparer
,在这种情况下:
.ToDictionary(g => g.Key, g => g.Count(), StringComparer.OrdinalIgnoreCase);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.