简体   繁体   English

C#递归转换为另一个类

[英]C# cast to another class with recursion

I am developing a MVC Project with Entity framework and i have a category table like this : 我正在开发带有实体框架的MVC项目,并且我有一个像这样的类别表:

public partial class Categories
{
    public Categories()
    {
        this.Categories1 = new HashSet<Categories>();
    }

    public int CategoryId { get; set; }
    public string CategoryName { get; set; }
    public Nullable<int> RelatedCategoryId { get; set; }

    public virtual ICollection<Categories> Categories1 { get; set; } //Children
    public virtual Categories Categories2 { get; set; } //Parent
}

When i get table data with EF, it gives me the object i want. 当我使用EF获取表数据时,它给了我想要的对象。 Parents with children. 有孩子的父母。

    class Program
    {
        static Entities db = new Entities();

        static void Main(string[] args)
        {
            List<Categories> categories = db.Categories.Where(item => item.RelatedId == null).ToList();
        }
}

With relatedId == null part, i get the main categories which has no parent. relatedId == null部分,我得到没有父级的主要类别。

There is no problem this far. 到目前为止没有问题。 But i want to cast categories object which ef returned to another class which is : 但是我想转换ef返回另一个categories对象:

public class NewCategories
{
    public int Id { get; set; }
    public string Name { get; set; }

    private List<NewCategories> _subCategories;

    public NewCategories()
    {
        _subCategories= new List<NewCategories>();
    }

    public List<NewCategories> SubCategories { get { return _subCategories; } }
}

And i want new List<NewCategories> newCategories object. 我想要新的List<NewCategories> newCategories对象。

How can i accomplish that? 我该怎么做?

Thanks. 谢谢。

I think you have to create a recursive method to convert Categories to NewCategories , something like this (I'm not sure if it works, but it's worth trying): 我认为您必须创建一个recursive方法才能将Categories转换为NewCategories ,类似这样(我不确定它是否有效,但是值得尝试):

public NewCategories ConvertToNewCategories(Categories cat){
  NewCategories nc = new NewCategories {Id = cat.CategoryId, Name = cat.CategoryName};
  nc.SubCategories.AddRange(cat.Categories1.Select(c=>ConvertToNewCategories(c)));
  return nc;
}
//Then
List<NewCategories> categories = db.Categories.Where(item => item.RelatedId == null)
                                              .Select(item=>ConvertToNewCategories(item))
                                              .ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM