gpt4 book ai didi

c# - Linq Group 结果到对象

转载 作者:太空狗 更新时间:2023-10-30 00:48:02 26 4
gpt4 key购买 nike

概览

当我上课时

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> 的结果? ?

我的 DotNetFiddle

最佳答案

为了实现这个目标,您可以在其中创建所需对象的 Select 方法。我认为这对您有用:

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();

关于c# - Linq Group 结果到对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50923146/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com