概述
当我上课时
public class RequestEntry
{
public int RequestId
{
get;
set;
}
public string ApproverUserId
{
get;
set;
}
public string ApproverUserName
{
get;
set;
}
public DateTime RequestedDate
{
get;
set;
}
}
它包含在List中:
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>
?
答案 0 :(得分:6)
要实现此目标,您可以选择具有创建所需对象的方法。 我认为这对你有用:
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()
RequestApprovers = g.Select(c => new RequestApprover(){ApproverUserName = c.ApproverUserName, ApproverUserId = c.ApproverUserId}).ToList()
}).ToList();