我有以下型号的清单
public class Participant{
public int Id{ get; set; }
public string Name{ get; set; }
public string Address{ get; set; }
}
输入值
Id Name Adress
1 Jhon America
2 Jhon Indonesia
3 Jhon Jerman
4 Okto Africa
4 Okto Arabic
5 Syahrul India
如何根据ID将列表转换为以下模型
public class Participant{
public int Id{ get; set; }
public string Name{ get; set; }
public List<Address> Address{ get; set; }
}
public class Address{
public string Name{ get; set; }
}
所以结果会像这样
Id Name Adress
1 Jhon America,Indonesia,Jerman
4 OKTO ARABIC,Africa
5 Syahrul India
我的方法是我将使用for循环,并且当ID相同时,我将添加地址,然后跳至下一个ID
但是我没有做到
有什么好的和有效的方法可以做到这一点
您可以按Id
和分组Name
。然后,您需要从每个组中选择新模型的实体。您可以从分组键中获得ID和名称,并且必须自行选择地址:
List<Participant_New> newModelCollection = participantCollection
.GroupBy(x => new {Id = x.Id, Name = x.Name})
.Select(g => new Participant_New
{
Id = g.Key.Id,
Name = g.Key.Name,
Address = g.Select(a => new Address{Name = a.Address}).ToList()
}).ToList();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句