我正在尝试列出医生的位置。每行包含医生信息以及位置。医生“ 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来实现,而不必遍历列表来手动填充新类?
答案 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();
此LINQ GroupBy
是您的ProviderLocation
,返回IGrouping
的列表,其密钥是ProviderId
和FirstName
的匿名对象。
每个IGrouping
(从group.Key
属性中获取)都会获得一名医生
然后我们在此Select
上进行IGrouping
,为此DoctorLocation
所包含的每个Item
返回一个IGrouping
。