我有以下课程:
public class ProviderQualification
{
public List<ProviderDetail> ProviderDetails { get; set; }
}
public class ProviderDetail
{
public string ProviderName { get; set; }
public string ServiceableOffers { get; set; }
}
public class ProviderQualificationTimeViewModel
{
public List<ProviderQualificationDetail> ProviderQualificationDetails { get; set; }
}
public class ProviderQualificationDetail
{
public string ProviderName { get; set; }
public string TotalServiceableOffers { get; set; }
}
我填充了ProviderQualification
的{{1}}个对象。
List<ProviderDetail>
现在我想将此列表复制到我的ProviderQualification providerQualification = reporting.GetProviderQualification();
。我该怎么做?
答案 0 :(得分:2)
使用Linq:
List<ProviderQualificationDetail> result =
providerQualification.ProviderDetails.Select(
q => new ProviderQualificationDetail()
{
ProviderName = q.ProviderName,
TotalServiceableOffers = q.ServiceableOffers
}).ToList();
使用Select
将ProviderDetails
中的每个元素投影到ProviderQualificationDetail
类型的新元素中,然后将其枚举为List
。
答案 1 :(得分:1)
您需要映射才能从ProviderDetail
转到ProviderQualificationDetail
。例如,如果您只想复制这些值,则可以像这样内联写入:
ProviderQualification providerQualification = reporting.GetProviderQualification();
var items = providerQualification.ProviderDetails
.Select(detail => new ProviderQualificationDetail
{
ProviderName = detail.ProviderName,
TotalServiceableOffers = detail.ServiceableOffers
})
.ToList();
var viewModel = new ProviderQualificationTimeViewModel
{
ProviderQualificationDetails = items
};
答案 2 :(得分:0)
您可以使用
Enumerable.Select&LT; TSource,TResult&gt;方法(IEnumerable&lt; TSource&gt;,Func&lt; TSource,TResult&gt;)
例如
List<ProviderQualificationDetail> list =
providerQualification.ProviderDetails
.Select(x => new ProviderQualificationDetail(){
ProviderName = x.ProviderName,
TotalServiceableOffers = x.ServiceableOffers
}).ToList();
答案 3 :(得分:0)
在我看来,@ zaria想要选择不同的ProviderName
和总ServiceableOffers
。如果她有ProviderQualification
课程,为什么要绑定到ProviderQualificationDetail
?
List<ProviderQualificationDetail> list=providerQualification.ProviderDetails.GroupBy(x => x.ProviderName)
.Select(x=>new ProviderQualificationDetail{
ProviderName =x.Key,
TotalServiceableOffers=Sum(y=>y.ServiceableOffers)
}).ToList();