如何使用子列表类将列表分组为新类

时间:2019-05-04 03:14:40

标签: c# linq

我正在尝试列出医生的位置。每行包含医生信息以及位置。医生“ A”可能有3个位置,因此医生“ A”将有3行。我想以某种方式使用linq组合该列表,以使用列表创建新的医生类。

Here is my initial list.  Each row duplicates ProviderId and Name if the provider has more than one location
var providerLocation = new List<ProviderLocation>
        {
            new ProviderLocation
            {
                ProviderId = "1",
                FirstName = "Provider1",
                AddressId = "1",
                City = "Des Moines"
            },
            new ProviderLocation
            {
                ProviderId = "1",
                FirstName = "Provider1",
                AddressId = "2",
                City = "Urbandale"
            },
            new ProviderLocation
            {
                ProviderId = "2",
                FirstName = "Provider2",
                AddressId = "3",
                City = "Dallas"
            },
            new ProviderLocation
            {
                ProviderId = "2",
                FirstName = "Provider2",
                AddressId = "4",
                City = "Fort Worth"
            }
        };

would like it to go into new classs that looks like:

 public class Doctor
 {
    public string ProviderId { get; set; }
    public string FirstName { get; set; }
    public List<DoctorLocation> Locations { get; set; }
 }

 public class DoctorLocation
 {
    public string AddressId { get; set; }
    public string City { get; set; }
 }

Then I could reference my doctor list by:
var doctorList = List<Doctor>

是否有一种方法可以使用linq来实现,而不必遍历列表来手动填充新类?

2 个答案:

答案 0 :(得分:0)

您可以使用ConvertAll方法。这是一种方法-

public static List<Doctor> MakeDoctorsListFrom(List<ProviderLocation> providerLocations)
    {
        return providerLocations.ConvertAll<Doctor>((input) => new Doctor()
        {
            ProviderId = input.ProviderId,
            FirstName = input.FirstName,
            Locations = new List<DoctorLocation>(){
                new DoctorLocation(){
                    AddressId = input.AddressId,
                    City = input.City
                }
            }
        });
    }

然后从代码中调用它-

var doctors = MakeDoctorsCollectionFrom(providerLocation);

答案 1 :(得分:0)

这会产生您想要的结果吗?

var doctorList = providerLocation
    .GroupBy(pl => new { pl.ProviderId, pl.FirstName })
    .Select(group => new Doctor()
    {
        ProviderId = group.Key.ProviderId,
        FirstName = group.Key.FirstName,
        Locations = group.Select(dl => new DoctorLocation()
        {
             AddressId = dl.AddressId,
             City = dl.City
        }).ToList()
    })
    .ToList();

结果: enter image description here

此LINQ GroupBy是您的ProviderLocation,返回IGrouping的列表,其密钥是ProviderIdFirstName的匿名对象。

每个IGrouping(从group.Key属性中获取)都会获得一名医生

然后我们在此Select上进行IGrouping,为此DoctorLocation所包含的每个Item返回一个IGrouping