c# - 如何从 linq 查询中过滤掉特定字段
问题描述
我有一个模型,其字段具有引用同一类的成员变量。现在我想查询数据及其子项,但我只想输出某些成员并过滤其他成员。
示例模型:
public class ContentModel
{
public string Name;
public string Url;
public string x, y, z // filter this
public IEnumerable<ContentModel> Children;
}
预期输出:
{
"Name": "",
"Url": "",
"Child": {
"Name": "",
"Url": "",
"Child": {
"Name": "",
"Url": ""
}
}
}
解决方案
我已经回答了数百次这样的问题。通常,您有一个平面数据库表,其中每一行都包含父母姓名和孩子姓名。然后你递归地创建一棵树。这是代码示例:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication108
{
class Program
{
static DataBase db = new DataBase();
static void Main(string[] args)
{
string parentName = string.Empty;
Tree root = new Tree();
GetTreeRecursively(parentName, root);
}
static void GetTreeRecursively(string parentName, Tree parent )
{
foreach (ContentModel model in db.contentModel.Where(x => x.parentName == parentName))
{
if (parent.children == null) parent.children = new List<Tree>();
Tree newChild = new Tree();
parent.children.Add(newChild);
newChild.url = model.url;
string name = model.name;
newChild.name = name;
GetTreeRecursively(name, newChild);
}
}
}
public class DataBase
{
public List<ContentModel> contentModel { get; set; }
}
public class ContentModel
{
public string parentName { get;set;}
public string url { get;set;}
public string x { get;set;}
public string y { get;set;}
public string z { get;set;}
public string name;
}
public class Tree
{
public string name { get; set; }
public string url { get; set; }
public List<Tree> children { get; set; }
}
}
推荐阅读
- reactjs - VSCode jsx 表达式格式化
- javascript - Javascript标签被忽略?
- reactjs - 服务器上收到的值与 POST 请求中发送的值不同
- regex - 如何重写现有的重写路径?
- excel - 有没有办法根据条件初始化公共数组?
- snowflake-cloud-data-platform - Snowflake 在双精度、浮点数、真实数据类型方面是否存在问题
- html - 我不知道如何在我的网站上创建响应式列?
- python - Python JSON 查找特定数据
- ide - 如何运行 GNAT 社区?
- python - 如何从 Python 中的现有文件在 Excel 中写入列标题