我的表格如下
Main_ID | Child_ID | Activity |
1 |1 | Start
1 |2 | Stop
1 |3 | Stop
2 |1 | Start
2 |3 | Stop
我正在寻找的是
Main_ID | Start | Stop
1 |1 |2
2 |1 |1
因此,在第一列中,我想要水平列出所有Main_Ids和不同的活动。之后,我想在Main_ID的每个活动下显示不同的Child_Ids的计数。
我试过的是
var result = from q in db.Table
where q.Child_ID != null
group 1 by new { q.Main_ID,q.Child_ID, q.Activity } into g
select new MyList
{
Main_ID = g.Key.Main_ID,
Child_ID = g.Key.Child_ID,
Activity = g.Key.Activity,
Count = g.Count()
}
into p orderby p.Main_ID,p.Child_ID select p;
但有了这个,我没有得到我所说的。
我使用以下
实现了Child_IDvar result2 = result.GroupBy(x => x.Child_ID)
.Select(grp => new MyList2
{
Child_ID = grp.Key,
StartCount = grp.Where(x => x.Activity == "Start")
.Select(x => x.Count).Cast<Int32>().FirstOrDefault(),
StopCount = grp.Where(x => x.Activity == "Stop")
.Select(x => x.Count).Cast<Int32>().FirstOrDefault()
});
不确定如何针对Main_ID显示它
答案 0 :(得分:3)
考虑这个课程:
public class Foo
{
public int Main_ID {get;set;}
public int Child_ID {get;set;}
public string Activity {get;set;}
}
有了这些数据:
var ls=new List<Foo>
{
new Foo{Main_ID=1,Child_ID=1,Activity="Start"},
new Foo{Main_ID=1,Child_ID=2,Activity="Stop"},
new Foo{Main_ID=1,Child_ID=3,Activity="Stop"},
new Foo{Main_ID=2,Child_ID=1,Activity="Start"},
new Foo{Main_ID=2,Child_ID=3,Activity="Stop"},
};
你可以这样做:
var result = ls
.GroupBy (g =>g.Main_ID)
.Select (g =>new
{
Main_ID = g.Key,
Start = g.Where(s=>s.Actvity == "Start").Select(x => x.Child_ID).Distinct().Count(),
Stop = g.Where(s=>s.Actvity == "Stop").Select(x => x.Child_ID).Distinct().Count(),
}
).ToList();
结果:
Main_ID Start Stop
1 1 2
2 1 1
答案 1 :(得分:0)
全部,
感谢您的帮助。
我可以使用以下
来做到这一点 var v = from q in myTable
where q.Child_ID != null
orderby q.ModifiedDate descending
select q;
var result2 = v
.GroupBy(g => new
{
g.Main_ID
})
.Select(grp => new MyClass
{
Main_ID = grp.Key.Main_ID,
StartCount = grp.Where(x=> x.Activity == "Start").Select(x => x.Child_ID).Distinct().Count(),
StopCount = grp.Where(x => x.Activity == "Stop").Select(x => x.Child_ID).Distinct().Count()
});
我正在使用此预期的resuts。
现在;我想知道这是否是正确的方法,如果两个查询可以合并。
因为它有代码,所以没有使用评论发布;抱歉: - )