1

In one of my c# requirement i have datatable in which i am having following data

Category Topics Resourceworked 
A        tp1    Hemant
A        tp2    Kevin
B        tp3    Haris
B        tp4    Hemant
B        tp5    Hemant
C        tp6    Kevin

In output i want two set of data

OutPut-1: For each unique category how many resorces worked

Category  NoOfResorces
A         2
B         2
C         1

Output-2: How many times resorces worked for unquie category like

Category  Resource   NoOfTime
A         Hemant     1
A         Kevin      1
B         Haris      1
B         Hemant     2
C         Kevin      1

What is the best way to achieve output i.e. either datatable filter or LINQ?

Addition: Can anyone LINQ expert will tell me good online website or book for learning LINQ?

Hemant Kothiyal
  • 4,092
  • 19
  • 61
  • 80

1 Answers1

1

Here is your first requirement:

var uniqueCat = from d in tblData.AsEnumerable()
                group d by (string)d["Category"] into Group
                select Group;
var catRes = from grp in uniqueCat
             let c = grp.Select(r => r["Resourceworked"]).Distinct().Count()
             select new {Category = grp.Key, NoOfResorces=c};

var summary = from cr in catRes
         select string.Format("Category:{0} Count:{1}",cr.Category,cr.NoOfResorces);
MessageBox.Show(string.Join(Environment.NewLine,summary));

This is the second query:

var uniqueCatRes = from d in tblData.AsEnumerable()
                   group d by new{Cat= d["Category"], Res=d["Resourceworked"]} into Group 
                   select Group;
var catResCount = from grp in uniqueCatRes
                  let Category = grp.Key.Cat
                  let Resource = grp.Key.Res
                  let NoOfResorces = grp.Count()
                  select new { Category,Resource,NoOfResorces };

summary = from crc in catResCount
          select string.Format("Category:{0} Resource:{1} Count:{2}", crc.Category,crc.Resource, crc.NoOfResorces);
MessageBox.Show(string.Join(Environment.NewLine,summary));
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939