我有一个班级
public class SelectionModel
{
public string Label { get; set; }
public int Value { get; set; }
}
public class RiskFactorModel
{
public SelectionModel RiskFactor { get; set; }
public int? RiskFactorIdParent { get; set; }
public List<string> RiskFactorNameChild { get; set; }
}
public List<RiskFactorModel> LowRiskFactorModel { get; set; }
我想更新LowRiskFactorModel。 检查每个Value(在SelectionModel下),如果两个或更多相同,则将RiskFactorNameChild合并为一个。
我如何在Linq中完成?
答案 0 :(得分:0)
您可以使用GroupBy
执行此操作,按SelectionModel.Value
对元素进行分组,然后创建新的RiskFactorModel
组合组中所有元素的子名称:
var groupedModels = LowRiskFactorModel.GroupBy(m => m.RiskFactor.Value);
var mergedModels = groupedModels.Select(g =>
new RiskFactorModel
{
RiskFactor = g.First().RiskFactor,
RiskFactorIdParent = g.First().RiskFactorIdParent,
RiskFactorNameChild = g.SelectMany(m => m.RiskFactorNameChild).ToList()
}).ToList();
结果是List<RiskFactorModel>
每个RiskFactor.Value
包含一个元素,其中RiskFactorNameChild
列表包含具有该名称的所有源元素的所有组合列表。
答案 1 :(得分:0)
请尝试以下操作:
public class RiskFactorModel
{
public static List<RiskFactorModel> LowRiskFactorModel { get; set; }
public string RiskFactorName { get; set; }
public List<string> RiskFactorNameChild { get; set; }
public void Update()
{
var groups = LowRiskFactorModel.GroupBy(x => x.RiskFactorName).ToList();
LowRiskFactorModel = groups.Select(x => new RiskFactorModel()
{
RiskFactorName = x.Key,
RiskFactorNameChild = x.Select(y => y.RiskFactorNameChild.Select(z => z)).SelectMany(y => y).Distinct().ToList()
}).ToList();
}
}