tags:

views:

26

answers:

1

I've got a bit of a situation with similar objects - basically, every object implements a collection of a base type. So ...

Item1 - List Items2 - List Items3

public List Specials { get; set; }

Item2 : Item1 Item3 : Item1

Special { public int Value { get; set; } public string Name { get; set; } }

Now, I can just go down the tree and get things - but I want to basically want to get all of the "special" class intances from the entire object, all the way down the tree - into one single collection.

Is this possible with LINQ? or do I just have to rely on very convoluted loops?

+2  A: 

You can use Linq in combination with recursive functions:

static IEnumerable<Special> getSpecials(Item1 item1)
{
    var item2Specials = item1.Items2.SelectMany(item2 => getSpecials(item2));
    var item3Specials = item1.Items3.SelectMany(item3 => getSpecials(item3));
    return item1.Specials.Concat(item2Specials).Concat(item3Specials);
}

It was a little difficult for me to understand your notation for your class structure. I'm assuming that you meant the following C# classes:

class Item1
{
    public List<Item2> Items2 = new List<Item2>();
    public List<Item3> Items3 = new List<Item3>();
    public List<Special> Specials = new List<Special>();
}

class Item2 : Item1 { }
class Item3 : Item1 { }

class Special
{
    public int Value { get; set; }
    public string Name { get; set; }
}

I am also assuming that you mean Linq-to-objects and not Linq-to-SQL. If you want to store heirarchical data in a database you should not do this but instead look at the nested set model.

Mark Byers
@Mark Byers +1. Very nice answer.
dcp