如何将父实例作为lambda select构造

时间:2016-09-28 02:20:16

标签: c# lambda

我正在尝试通过lambda select创建模型列表 并且有一些嵌套模型,我想在一次构建它们 但我不知道在进行构造时如何将父实例传递给子属性

         SubCategories = cc.OrderBy(c => c.ProductCategory.Sequency)
            .Select(c => new ProductCatetoryListViewModel.Category()
            {
                Models = items.Where(i => i.ProductItem.CategoryID == c.CategoryID).GroupBy(i => i.ProductItem.Model)
                    .Select(mg => new ProductCatetoryListViewModel.Model
                    {
                        Name = mg.Key,
                        Products = mg.Select(i => i.ProductItem).OrderBy(i => i.Sequency).ToArray(),
                        //Category =  ???? i want this to be the newly constructed ProductCatetoryListViewModel.Category which owns this model list
                    }).ToArray(),
                Title = c.ProductCategory.Title,
                Name = c.Name,
            }).ToArray()

基于@Enigmativity的回答 更新的代码工作正常

 SubCategories = cc.OrderBy(c => c.ProductCategory.Sequency)
            .Select(c => new ProductCatetoryListViewModel.Category(items, c)
            {
                Title = c.ProductCategory.Title,
                Name = c.Name,
            }).ToArray()

构造函数是

public Category(ProductItemCultured[] items, ProductCategoryCultured c)
        {
            Models = items.Where(i => i.ProductItem.CategoryID == c.CategoryID).GroupBy(i => i.ProductItem.Model)
            .Select(mg => new Model
            {
                Name = mg.Key,
                Products = mg.Select(i => i.ProductItem).OrderBy(i => i.Sequency).ToArray(),
                Category = this,
            }).ToArray();

        }

0 个答案:

没有答案