概述
当我有一个类作为:
public class RequestEntry
{
public int RequestId
{
get;
set;
}
public string ApproverUserId
{
get;
set;
}
public string ApproverUserName
{
get;
set;
}
public DateTime RequestedDate
{
get;
set;
}
}
并且它包含在一个列表中,如下:
List<RequestEntry> RequestEntries = new List<RequestEntry>()
{
new RequestEntry{RequestId = 1, RequestedDate = new DateTime(2018,06,01), ApproverUserId = "STEVES", ApproverUserName = "Steve Smith"},
new RequestEntry{RequestId = 1, RequestedDate = new DateTime(2018,06,01), ApproverUserId = "GRAHAMS", ApproverUserName = "Graham Smith" },
new RequestEntry{RequestId = 2, RequestedDate = new DateTime(2018,06,02), ApproverUserId = "STEVES", ApproverUserName = "Steve Smith"},
new RequestEntry{RequestId = 3, RequestedDate = new DateTime(2018,06,03), ApproverUserId = "ROBINS", ApproverUserName = "Robin Smith"},
new RequestEntry{RequestId = 3, RequestedDate = new DateTime(2018,06,03), ApproverUserId = "CHRISS", ApproverUserName = "Chris Smith"},
new RequestEntry{RequestId = 3, RequestedDate = new DateTime(2018,06,03), ApproverUserId = "LIAMS", ApproverUserName = "Liam Smith"}
};
目标
我的期望结果是:
public class RequestWithApprover
{
public int RequestId
{
get;
set;
}
public DateTime RequestedDate
{
get;
set;
}
public List<string> ApproverUserIds
{
get;
set;
}
public List<RequestApprover> RequestApprovers
{
get;
set;
}
}
其中RequestApprover
的定义如下
public class RequestApprover
{
public string ApproverUserId
{
get;
set;
}
public string ApproverUserName
{
get;
set;
}
}
工作原理
在跟随Stackoverflow中的一些早期情景之后,我能够撰写代码以获取一个已定义为List的结果。
var results = (
from r in RequestEntries
group r by new
{
r.RequestId, r.RequestedDate
}
into g
select new RequestWithApprover()
{
RequestId = g.Key.RequestId,
RequestedDate = g.Key.RequestedDate,
ApproverUserIds = g.Select(c => c.ApproverUserId).ToList()
//----> Here I am able to get a List<string> but need to be in List<RequestWithApprover>
}).ToList();
我该如何获得 List<RequestWithApprover>
的结果?