开发者

Map Hierarchical Collection of Domain Objects to Hierarchical Collection of ViewModels

I am trying to think of an efficient approach to iterating through a hierarchical collection of domain objects and map them to their corresponding view models.

Assume that I have the following two types of domain objects:

(1) Folder - this object has two collections - one collection of folder objects and one collection of Item objects.

(2) Item

Now, I have two view model classes - one for the Folder domain object and one for the Item object. I want to be able to efficiently iterate through my entire hierarchical collection, and based on whether the object is a Folder or an item, I will create a new view model class for the corresponding domain object and pass the object into the view model's constructor. Basically, I want to end up with a hierarchical view model representation of the hierarchical domain object collection. I know I can do this with some nested for eaches, but I thought that someone may know of a way using extension methods,开发者_Python百科 linq, and lambda.

Thanks for your help.


you can use a LINQ query like that to union the two collections:

public class Folder
{
}

public class Item
{
}

public IEnumerable<Object> GetChildren()
{

    Folder[] Folders = new Folder[] { };
    Item[] Items = new Item[] { };

    return ((IEnumerable<Object>)(from Folder folder in Folders 
                                  select folder))
                                  .Union<Object>(
           (IEnumerable<Object>)(from Item item in Items select item));
}

if you have a common base class its for sure better to use it instead of "Object"


I guess you are looking for something like this:

public class FolderVM
{
  public string Name {get; private set;}      

  public IEnumerable<FolderVM> Folders { get; private set; }
  public IEnumerable<ItemVM> Items { get; private set; }

  public FolderVM(Folder folder)
  {
    Name = folder.Name;

    Folders = folder.ChildFolders.Select(f=> new FolderVM(f));
    Items = folder.Items.Select(i=> new ItemVM(i));
  }
}

And the rendering will probably be recursive respectively.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜