[英]Lambda Expression LINQ Equivalent to SQL Exists Query on Same Table/Variable
[英]SQL query to Linq Lambda Expression - Join same table with group condition
任何人都可以幫助將以下SQL查詢轉換為c#LinQ Lambda Expression? 謝謝
tbl_CLASS
ClassID Student
Class1 A
Class1 B
Class1 C
Class2 B
Class2 C
Class3 C
結果
Class A B C
Class1 Y Y Y
Class2 N Y Y
Class3 N N Y
SELECT a.ClassID,
A=case when c.ClassID is null then 'N' else 'Y' end,
B=case when B.ClassID is null then'N' else 'Y' end,
C='Y'
FROM tbl_CLASS a
Left join tbl_CLASS b on a.ClassID=b.ClassID AND b.Student='B'
Left join tbl_CLASS c on a.ClassID=c.ClassID AND c.Student='A'
WHERE a.Student='C'
GROUP by a.ClassID,case when c.ClassID is null then 'N' else 'Y' end,case when B.ClassID is null then'N' else 'Y' end
List<Class1> myList = GetClass();
var query = myList
.GroupBy(c => c.ClassID)
.Select(g => new {
ClassID = g.Key,
A = g.Count(c => c.Student=="A")>0?"Y":"N",
B = g.Count(c => c.Student=="B")>0?"Y":"N",
C = g.Count(c => c.Student=="C")>0?"Y":"N"
});
GetClass是獲取您的數據
public class Class1
{
public Int32 ClassID {get;set;}
public String A{get;set;}
public String B{get;set;}
public String C{get;set;}
}
當學生是動態的時,意味着你需要一個結果行的結果類,如下所示:
class ResultRow
{
public ResultRow()
{
Students = new Dictionary<string, string>();
}
public string Class { get; set; }
public IDictionary<string, string> Students { get; set; }
}
因為您需要為學生提供動態列。
現在,我可以使用以下代碼生成與預期結果類似的結果:
var res = tblClass
.GroupBy(g=> g.ClassId)
.Select(c =>
{
var rr = new ResultRow {Class = c.Key};
foreach (var r in tblClass.GroupBy(gg=> gg.Student))
{
rr.Students[r.Key] = "N";
}
foreach (var r in c.Where(w=> w.ClassId == c.Key))
{
rr.Students[r.Student] = "Y";
}
return rr;
})
.toList(); //optional
您還可以將這兩個方法添加到ResultRow
類:
public string GetHeader()
{
return Students.Aggregate("Class", (current, s) => current + "|" + s.Key);
}
public string GetSolidRow()
{
return Students.Aggregate(Class, (current, s) => current + "|" + s.Value);
}
[ Demo Here
]
HTH
無法從System.Collections.Generic.List <>轉換為System.Collections.Generic.IEnumerable <>
public SystemAccessList GetAccessList(SystemAccessList systemAccessList)
{
var qresult = db.tbl_SystemAccessList
.GroupBy(g => g.ClassID)
.AsEnumerable().Select(c =>
{
var rr = new ResultRow { Class = c.Key };
foreach (var r in db.tbl_SystemAccessList.GroupBy(gg => gg.StudentID))
{
rr.Student[r.Key] = "N";
}
foreach (var r in c.Where(w => w.ClassID == c.Key))
{
rr.Student[r.StudentID] = "Y";
}
return rr;
}).ToList();
systemAccessList.SystemAccessList.AddRange(qresult);
return systemAccessList;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.