c# - 如果满足父列表中子项列表中的列表内的属性,则返回父列表中的项
问题描述
我正在尝试用下面给出的代码中的 LINQ 替换 foreach。我已经更正了代码并添加了一些演示数据。希望这能澄清一点。
我必须以这样一种方式进行过滤,即 LINQ 查询返回包含至少一个满足爱好条件检查的项目的父项目。
var parents = new List<Parent>
{
new Parent
{
ParentName = "Tom",
Children = new List<Child>
{
new Child
{
ChildName = "Ram",
Hobbies = new List<Hobby>
{
new Hobby
{
Name = "Reading",
Code = "1"
},
new Hobby
{
Name = "Hiking",
Code = "2"
}
}
}
}
},
new Parent
{
ParentName = "Harry",
Children = new List<Child>
{
new Child
{
ChildName = "Som",
Hobbies = new List<Hobby>
{
new Hobby
{
Name = "Exercise",
Code = "2"
},
new Hobby
{
Name = "Hiking",
Code = "3"
}
}
}
}
}
};
var parentsWithKidsWhoDontExercise = new List<Parent>();
foreach(var parent in parents)
{
foreach(var child in parent.Children)
{
var favoriteHobby = child.Hobbies.FirstOrDefault();
if(favoriteHobby.Name !="Exercise")
{
parentsWithKidsWhoDontExercise.Add(parent);
}
}
}
解决方案
我今天早些时候回答了一个类似的问题。请参阅下面的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<Parent> parents = new List<Parent>() {
new Parent() { ID = 123, Children = new List<Child>() {
new Child() { ID = 2000, Hobbies = new List<Hobby>() {
new Hobby() { HobbyName = "Stamp Collection", ID = 3000},
new Hobby() { HobbyName = "Coins Collection", ID = 3001},
new Hobby() { HobbyName = "Butterfly Collection", ID = 3002}
}
},
new Child() { ID = 2001, Hobbies = new List<Hobby>() {
new Hobby() { HobbyName = "Stamp Collection", ID = 3000},
}
},
new Child() { ID = 2002, Hobbies = new List<Hobby>() {
new Hobby() { HobbyName = "Coins Collection", ID = 3001},
}
},
new Child() { ID = 2003, Hobbies = new List<Hobby>() {
new Hobby() { HobbyName = "Butterfly Collection", ID = 3002}
}
}
}
}
};
var parentItems = parents.SelectMany(x => x.Children.SelectMany(y => y.Hobbies.Select(z => new { parentId = x.ID, childId = y.ID, hobbyName = z.HobbyName, hobbyId = z.ID }))).ToList();
}
}
public class Parent
{
public int ID { get;set;}
public List<Child> Children { get;set;}
}
//Nested class 1
public class Child
{
public int ID { get; set; }
public List<Hobby> Hobbies { get; set; }
}
//Nested class 2
public class Hobby
{
public int ID { get; set; }
public string HobbyName { get; set; }
}
}
推荐阅读
- c# - 单击按钮时值变为负一
- r - 在 R 中 geom_histogram() 到 hist()
- javascript - 未捕获的错误:无效的挂钩调用。Hooks 只能在函数组件的主体内部调用
- c# - iTextSharp PdfContentByte AddTemplate
- r - 控制台输出与针织 pdf 输出不匹配
- svg - SVG参数实现的现状
- javascript - 具有可变路由回报的函数
- reactjs - 更新嵌套的 useState 似乎修改了原始数据
- python - 带有 CUDA 8.0 的 Colab 返回 GPU 未找到错误
- database - 有什么办法吗,我将在 xquery 文件的顶部设置数据库而不将其传递给 spawn/eval/invoke