在我的一个c#要求中,我有数据表,其中我有以下数据
Category Topics Resourceworked
A tp1 Hemant
A tp2 Kevin
B tp3 Haris
B tp4 Hemant
B tp5 Hemant
C tp6 Kevin
在输出中我想要两组数据
OutPut-1:对于每个独特的类别,有多少个resorces工作
Category NoOfResorces
A 2
B 2
C 1
输出-2:对于像
这样的unquie类别,resorces工作了多少次Category Resource NoOfTime
A Hemant 1
A Kevin 1
B Haris 1
B Hemant 2
C Kevin 1
实现输出的最佳方法是什么,即数据表过滤器或LINQ?
增加: 任何LINQ专家都能告诉我好的在线网站或学习LINQ的书吗?
答案 0 :(得分:1)
这是您的第一个要求:
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));
这是第二个查询:
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));