[英]Adding another table to a grouped linq query
我有兩張桌子
Person
__________
PersonID
PersonName
DOB
Status
Notes
__________
NoteID
PersonID
NoteText
Comments
LineNo
這是一些樣本內容
PersonID PersonName DOB Status
1 Mark Jacobs 07/07/1961 Active
和
NoteID PersonID NoteText LineNo
123 1 Line 1 1
234 1 Line 2 2
236 1 Line 3 3
因此,最終結果是我希望Linq查詢顯示類似的內容
PersonID PersonName DOB Note
1 Mark Jacobs 07/07/1961 Line 1, Line 2, Line 3
我對Notes表有一個有效的linq查詢,但也想包括Persons表中的一些字段:
var result = (from n in db.Notes
group n.NoteText by n.PersonID into g
select new {
PersonID = g.Key,
Notes = g.ToList()
}).AsEnumerable()
.Select(item => new NoteGroupDTO {
PersonID = item.PersonID,
Notes = string.Join(", ", item.Notes)
}).ToList();
我想將“人名”,“ DOB”和“狀態”添加到選擇列表中。
我創建了一個班
public class PersonNoteDTO
{
public int PersonID { get; set; }
public string PersonName { get; set; }
public DateTime DOB { get; set; }
public string Status { get; set; }
public string Notes { get; set; }
}
在查詢中,我添加了一個join和order by子句以按行號排序。 但是我不確定如何將字段添加到匿名對象的選擇列表中:
var result = (from n in db.Notes
join p in db.Persons on n.PersonID=p.PersonID
orderby n.LineNo
group n.NoteText by n.PersonID into g
select new {
PersonID = g.Key,
Notes = g.ToList()
}).AsEnumerable()
.Select(item => new PersonNoteDTO {
PersonID = item.PersonID,
Notes = string.Join(", ", item.Notes)
}).ToList();
您可以按多個字段分組,然后通過.Key
屬性訪問以下屬性:
var result = (from n in db.Notes
join p in db.Persons on n.PersonID equals p.PersonID
group new { n.NoteText, n.LineNo } by new { n.PersonID, n.PersonName, p.DOB, p.Status } into g
select new {
PersonID = g.Key.PersonID,
PersonName = g.Key.PersonName,
DOB = g.Key.DOB,
Status = g.Key.Status,
Notes = g.OrderBy(i => i.LineNo).Select(i=> i.NoteText)
}).AsEnumerable()
.Select(item => new PersonNoteDTO {
PersonID = item.PersonID,
PersonName = item.PersonName,
DOB = item.DOB,
Status = item.Status,
Notes = string.Join(", ", item.Notes)
}).ToList();
如果所有這些屬性確實是Person
類的一部分,那么您也可以只是GroupJoin
:
var result = (from p in db.Persons
join n in db.Notes on p.PersonID equals n.PersonID into personNotes
select new
{
Person = p,
Notes = personNotes.OrderBy(pn => pn.LineNo).Select(pn => pn.NoteText)
}).AsEnumerable()
.Select(item => new PersonNoteDTO {
PersonID = item.Person.PersonID,
PersonName = item.Person.PersonName,
DOB = item.Person.DOB,
Status = item.Person.Status,
Notes = string.Join(", ", item.Notes)
}).ToList();
但我建議您研究導航屬性。 然后,您甚至不需要加入。 只要有一個.Include
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.