首页 > 解决方案 > 如何从 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": ""
    }
  }
}

标签: c#linq

解决方案


我已经回答了数百次这样的问题。通常,您有一个平面数据库表,其中每一行都包含父母姓名和孩子姓名。然后你递归地创建一棵树。这是代码示例:

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; }
    }
}

推荐阅读