有父母的孩子名单转换成父母与孩子的名单

时间:2011-11-22 20:16:37

标签: c# .net lambda

我有一些模型设置如下:

public class Form
{
    public int FormId { get; set; }
    public virtual ICollection<SubForm> SubForms{ get; set; }
}
public class SubForm
{
    public int SubFormId { get; set; }
    public virtual Form Form {get; set;}
}

我有一个这样的清单:

List<SubForm> subForms; <-- already populated, each subform has a form parent.

如何以最佳格式(lambda首选)获取它

List<Form> formsWithChildren;

3 个答案:

答案 0 :(得分:1)

formsWithChildren = subForms.Select(x => x.Form).Distinct().ToList();

这是你的意思吗?

答案 1 :(得分:0)

不创建新表单对象的方法:

        //Populate subForms list of the forms
        subForms.GroupBy(x => x.Form).ForEach(x => x.Key.SubForms = x.ToList());
        //Select forms
        var forms = subForms.Select(x => x.Form).Distinct().ToList();

答案 2 :(得分:0)

您可以按FormId进行分组,然后将分组的子表单分配给每个新的Form项,如下所示:

var formsWithChildren = subForms.GroupBy(s => s.Form.FormId)
                                .Select(g => new Form
                                {
                                    FormId = g.Key,
                                    SubForms = g.ToList()
                                }).ToList();

编辑:如果存在其他属性,则必须在对象初始化程序中映射它们,但这可能会变得乏味,如果您打算重用此类型,则不是最佳选择在其他场景中的查询。我建议您创建一个新的Form对象并使用AutoMapper映射它。

如果您决定使用AutoMapper,则方法类似于:

var formsWithChildren = new List<Form>();
foreach (var item in subForms.GroupBy(s => s.Form))
{
    Form f = Mapper.Map<Form, Form>(item.Key);
    f.SubForms = item.Select(s => s).ToList();
    formsWithChildren.Add(f);
}

要了解详情,请参阅AutoMapper site

或者,您可以采取如下方法,虽然这会修改现有项目,因此请注意这一点。

var formsWithChildren = new List<Form>();
foreach (var item in subForms.GroupBy(s => s.Form))
{
    // re-use existing Form from grouping so it retains its assigned values
    Form f = item.Key;
    f.SubForms = item.Select(s => s).ToList();
    formsWithChildren.Add(f);
}

在上面显示的两种方法中,您需要在Equals课程上实施Form,以便对Form而不是FormId进行分组:

public class Form
{
    public int FormId { get; set; }
    public virtual ICollection<SubForm> SubForms{ get; set; }

    public override bool Equals(object obj)
    {
        if (obj == null)
            return false;

        Form f = obj as Form;            
        return this.Equals(f);
    }

    public bool Equals(Form f)
    {
        if (f == null)
            return false;

        return this.FormId == f.FormId;
    }

    public override int GetHashCode()
    {
        return this.FormId.GetHashCode();
    }
}

您可以扩展相等和GetHashCode方法以使用属性来确定唯一性。目前它只依赖于FormId