从datatable计算组的百分比 [英] Calculating percentage of a groups from datatable
本文介绍了从datatable计算组的百分比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 datatable
,如下所示
组名可以是A,B,C等...
如何根据该数据值计算数字?
解决方案
你可以使用LINQ并将其转换为字典:
DataTable dt = new DataTable(test1);
dt.Columns.AddRange(new DataColumn [] {new DataColumn(TASKID),新的DataColumn(GROUPID),新的DataColumn(GROUPNAME)});
dt.Rows.Add(new object [] {12,2,A});
dt.Rows.Add(new object [] {13,3,B});
dt.Rows.Add(new object [] {12,2,A});
dt.Rows.Add(new object [] {14,3,null});
dt.Rows.Add(new object [] {15,3,B});
var query =(从dt.Rows
中的DataRow行按行[GROUPNAME]转换为g
选择g).ToDictionary(x =>(x.Key.ToString ()==?*:x.Key.ToString()),x =>(int)((x.Count()* 100)/ dt.Rows.Count));
通过字典迭代显示值:
Console.WriteLine(kvp.Key + - + kvp.Value.ToString()); $ {pre>
foreach(KeyValuePair< string,int> kvp in query)
输出:
A - 40
B - 40
* - 20
百分比被转换为int。只需更改(int)((x.Count()* 100)/ dt.Rows.Count)
如果您需要更准确的值。
I have a datatable
that looks like below
My result Should be A=40% , B=60% .. ie 2/5 and 3/5 Group name can be A, B, C, etc...
How can i calculate the figures based on that datatable values??
解决方案
You could use LINQ and cast it to a dictionary:
DataTable dt = new DataTable("test1");
dt.Columns.AddRange(new DataColumn[] { new DataColumn("TASKID"), new DataColumn("GROUPID"), new DataColumn("GROUPNAME") });
dt.Rows.Add(new object[] { 12, 2, "A" });
dt.Rows.Add(new object[] { 13, 3, "B" });
dt.Rows.Add(new object[] { 12, 2, "A" });
dt.Rows.Add(new object[] { 14, 3, null });
dt.Rows.Add(new object[] { 15, 3, "B" });
var query = (from DataRow row in dt.Rows
group row by row["GROUPNAME"] into g
select g).ToDictionary(x => (x.Key.ToString() == "" ? "*" : x.Key.ToString()), x => (int)((x.Count() * 100) / dt.Rows.Count));
Iterate through the dictionary to display the values:
foreach(KeyValuePair<string,int> kvp in query)
Console.WriteLine(kvp.Key + " - " + kvp.Value.ToString());
The output:
A - 40
B - 40
* - 20
The percentage is cast as an int. simply change (int)((x.Count() * 100) / dt.Rows.Count)
if you need more accurate values.
这篇关于从datatable计算组的百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文