在c#中将List对象赋值给另一个List对象
本文关键字:对象 List 另一个 赋值 中将 | 更新日期: 2023-09-27 18:18:21
我有以下类:
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; }
}
我用List<ProviderDetail>
填充ProviderQualification
对象。
ProviderQualification providerQualification = reporting.GetProviderQualification();
现在我想把这个列表复制到我的List<ProviderQualificationDetail>
。我该怎么做呢?
Using Linq:
List<ProviderQualificationDetail> result =
providerQualification.ProviderDetails.Select(
q => new ProviderQualificationDetail()
{
ProviderName = q.ProviderName,
TotalServiceableOffers = q.ServiceableOffers
}).ToList();
使用Select
,您将ProviderDetails
中的每个元素投影到ProviderQualificationDetail
类型的新元素中,然后将其枚举到List
中。
需要一个从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
};
可以使用
例如Enumerable.Select<TSource,> Method (IEnumerable
, Func<TSource,>)
List<ProviderQualificationDetail> list =
providerQualification.ProviderDetails
.Select(x => new ProviderQualificationDetail(){
ProviderName = x.ProviderName,
TotalServiceableOffers = x.ServiceableOffers
}).ToList();
在我看来,@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();