Q:

Calculating percentage of a groups from datatable

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??

A:

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.

