C# 使用Linq的透视表
我有一个这样的表。(VisitType是动态的) 我想使用linq获得一个轴,如下所示C# 使用Linq的透视表,c#,linq,group-by,pivot,pivot-table,C#,Linq,Group By,Pivot,Pivot Table,我有一个这样的表。(VisitType是动态的) 我想使用linq获得一个轴,如下所示 VisitDate PersonelId A S D B 2015-02-22 4 0 2 0 0 2015-02-22 2 1 1 0 0 2015-02-23 2 0 1 0 0 2015-02-23
VisitDate PersonelId A S D B
2015-02-22 4 0 2 0 0
2015-02-22 2 1 1 0 0
2015-02-23 2 0 1 0 0
2015-02-23 3 1 0 0 0
2015-02-23 1 1 0 0 0
2015-02-24 1 1 0 1 0
2015-02-24 2 0 0 1 0
2015-02-24 4 0 1 0 0
2015-02-24 3 0 0 1 0
我用这个linq
var d = (from f in _db.Visits
group f by new {f.VisitDate, f.PersonnelId }
into myGroup
where myGroup.Count() > 0
select new
{
myGroup.Key.VisitDate,
myGroup.Key.PersonnelId,
subject = myGroup.GroupBy(f => f.VisitTypeId).Select
(m => new { Sub = m.Count(), Score = m.Sum(c => c.Amount) })
}).ToList();
它是按日期和个人id分组的,但不要对每个访问类型中的项目进行计数。尝试以下方法:
//static headers version
var qry = Visits.GroupBy(v=>new{v.VisitDate, v.PersonelId})
.Select(g=>new{
VisitDate = g.Key.VisitDate,
PersonelId = g.Key.PersonelId,
A = g.Where(d=>d.VisitTypeId=="A").Count(),
B = g.Where(d=>d.VisitTypeId=="B").Count(),
D = g.Where(d=>d.VisitTypeId=="D").Count(),
S = g.Where(d=>d.VisitTypeId=="S").Count()
});
//dynamic headers version
var qry = Visits.GroupBy(v=>new{v.VisitDate, v.PersonelId})
.Select(g=>new{
VisitDate = g.Key.VisitDate,
PersonelId = g.Key.PersonelId,
subject = g.GroupBy(f => f.VisitTypeId)
.Select(m => new { Sub = m.Key, Score = m.Count()})
});
首先为以下人员获取动态访问类型
var VisTyp= (from VT in _db.VisitType select new{VisType=VT.VisitType} ).ToList();
然后使用以下命令
var d = (from f in _db.Visits
group f by new {f.VisitDate, f.PersonnelId } into myGroup
where myGroup.Count() > 0
select new
{
VisitDate = myGroup.Key.VisitDate,
PersonnelId = myGroup.Key.PersonnelId,
subject=myGroup.Count(t => VisTyp.Contains(t.VisitType))
}).ToList();
谢谢,但是VisitType是动态的(它是另一个表的外键)。你说的“VisitType是动态的”是什么意思?我有两个模型,Visit和VisitType。该visittype是visit表中的外键
var d = (from f in _db.Visits
group f by new {f.VisitDate, f.PersonnelId } into myGroup
where myGroup.Count() > 0
select new
{
VisitDate = myGroup.Key.VisitDate,
PersonnelId = myGroup.Key.PersonnelId,
subject=myGroup.Count(t => VisTyp.Contains(t.VisitType))
}).ToList();