如果父ID相同,则Linq查询合并子项

时间:2017-02-02 17:12:36

标签: c# linq

我有一个班级

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中完成?

2 个答案:

答案 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();
        }

    }