C#LINQ按性别查询子项,按父项性别查询组

时间:2017-04-26 01:09:45

标签: c# linq

我必须使用下面的列表中的LINQ进行查询。

[{
    "name": "Bob",
    "gender": "Male",   
    "children": [{
        "name": "Aron",
        "gender": "Male"
    }, {
        "name": "Jaime",
        "gender": "Female"
    }]
}, {
    "name": "Jennifer",
    "gender": "Female", 
    "children": [{
        "name": "Greg",
        "gender": "Male"
    }]
}, {
    "name": "Steve",
    "gender": "Male",   
    "children": null
}, {
    "name": "Fred",
    "gender": "Male",   
    "children": [{
        "name": "Tom",
        "gender": "Male"
    }, {
        "name": "Max",
        "gender": "Male"
    }, {
        "name": "Sam",
        "gender": "Female"
    }, {
        "name": "Jim",
        "gender": "Male"
    }]
}, {
    "name": "Samantha",
    "gender": "Female", 
    "children": [{
        "name": "Andrew",
        "gender": "Male"
    }]
}, {
    "name": "Alice",
    "gender": "Female", 
    "children": [{
        "name": "John",
        "gender": "Male"
    }, {
        "name": "Samantha",
        "gender": "Female"
    }]
}]

我需要有女性子女的父母,并按父母性别分组(如下所示)

[{      
    "gender": "Male",           
        "name": "Jaime",
        "gender": "Female"
    }]
},
{
    "name": "Fred",
    "gender": "Male",   
    "children": [{
        "name": "Sam",
        "gender": "Female"
    }]
} , {
    "name": "Alice",
    "gender": "Female", 
    "children": [{
        "name": "Samantha",
        "gender": "Female"
    }]
}]

请您告诉我如何使用LINQ

进行操作

修改

public class Parent
{
    public int ParentID {get; set;}
    public string Name {get; set;}
    public string Gender {get; set;}
    public List<Child> Children {get; set;}
}

public class Child
{
    public int ChildID {get; set;}
    public string Name {get; set;}
    public string Gender {get; set;}
    public DateTime DateOfBirth {get; set;}
}

我有一个带有上面json数据的Parent列表,希望能够制作场景

var newlist = parents.where(p=> p.Children !=null && p.Children.Any(c=>     c.Gender=="Female" ))

修改 如果您想获得如下结果

,该怎么办?
[{      
    "gender": "Male",   
     "children": [{        
        "name": "Jaime"       
    }]
},
{    
    "gender": "Female",   
    "children": [{
        "name": "Sam",
        "name": "Samantha",
    }]
}]

由于

1 个答案:

答案 0 :(得分:0)

var newlist = 
              Parents
              .Where(p.Children.Any(c=> c.Gender == "Female"))
              .Select(p => p.Parent)
              .ToList();