1

Which is the best way to get a list of a recursive earch on Linq.

For example if I have a Category class that can have other categories as a child and the categories have products as its childs, something like

Category1 > Product1
          > Product2

Category2 > Product3
          > Category21 > Product31
                       > Product32
          > Product4

and so on, and I need to return the Ids of al categories and products in a list. Is there any way to achieve this?

Yatiac
  • 1,820
  • 3
  • 15
  • 25
  • 1
    Yes there is. Have you searched for "recursive linq" or anything along those lines? – D Stanley Dec 22 '15 at 15:19
  • @DStanley yes I have, but I only need a single list with all the Ids, not the object hierarchy. – Yatiac Dec 22 '15 at 15:20
  • 3
    Keep searching and try to apply those solutions and ask specific questions when you're stuck. There's not a "magic bullet" that solves your query, so you need to show what you've attempted and provide more detail about your data structure to get a valid answer. – D Stanley Dec 22 '15 at 15:22
  • Do you want a unique list of Ids from two different tables/entities? – E-Bat Dec 22 '15 at 17:00
  • @E-Bat that is right. – Yatiac Dec 22 '15 at 18:53
  • Please, show the exact structure of your entities or database. Without seeing it is nearly impossible to answer your question – JotaBe Dec 23 '15 at 09:25
  • Take a look at http://stackoverflow.com/a/20975582/4903929 – Skuzzbox Dec 23 '15 at 16:12

1 Answers1

1

First, in your situation, models should look like this:

public class Product
{
    public int id { get; set; }
    public string name { get; set; }

    public virtual Category Category { get; set; }
    public int CategoryID { get; set; }
}

public class Category
{
    public int id { get; set; }
    public string name { get; set; }

    public virtual ICollection<Product> Products { get; set; }
    public virtual ICollection<Category> Categories { get; set; }

    public virtual Category Parent { get; set; }
    public int? ParentID { get; set; }

    private List<int> GetIds(Category category)
    {            
        var list = Products == null ? new List<int>() : Products.Select(x => x.id).ToList();
        if (Categories != null)
            Categories.ToList().ForEach(x => {
                list.Add(x.id);
                list.AddRange(x.GetIds(x));
            }
        );            
        return list;
    }

    public List<int> GetIds()
    {
        return GetIds(this);
    }
}

And you will execute it this way:

var db = new DataContext();
//switching on "LazyLoading" is extremely necessary
db.Configuration.LazyLoadingEnabled = true;

var first = db.Categories.Where(x => x.id == 5).First();
var ids = first.GetIds();
Slava Utesinov
  • 13,410
  • 2
  • 19
  • 26