将List对象分配给c#中的另一个List

时间:2016-11-16 07:45:57

标签: c# list object

我有以下课程:

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(); 。我该怎么做?

4 个答案:

答案 0 :(得分:2)

使用Linq:

List<ProviderQualificationDetail> result = 
         providerQualification.ProviderDetails.Select(
                         q => new ProviderQualificationDetail() 
                                   { 
                                       ProviderName  = q.ProviderName, 
                                       TotalServiceableOffers = q.ServiceableOffers 
                                   }).ToList();

使用SelectProviderDetails中的每个元素投影到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();