Linq选择新的动态多部分列表<>

时间:2015-05-25 12:28:26

标签: c# linq refactoring

我正在使用以下查询:

public void FindAllRelatedProdsByParentCat(CategoryService categoryService, string parentCatName, bool isDeleted)
{
    List<Category> allCats = categoryService.FindAll(isDeleted).ToList();

    var results = (from a in allCats.Where(x => x.Name == parentCatName)
                   join b in allCats 
                   on a.CategoryId equals b.Parentcategory into children
                   select new 
                         { 
                           ParentId = a.CategoryId, 
                           ChildrenIds = children.Select(z => z.CategoryId) 
                         }).ToList();
}

理想情况下,我希望将select new语句压缩为一般类型的Id对象列表。目前我不得不用两个属性组成一个匿名对象来获得我想要的东西。可以帮我把它重构成一个单一的列表吗?这可以吗?

更新: 类别实体的样子:

public class Category : EntityBase
{
    public Category()
    {
        Products = new List<Product>();
    }

    public Guid CategoryId { get; set; }
    public string Name { get; set; }
    public Guid? Parentcategory { get; set; }
    public bool IsDeleted { get; set; }
    public Guid OrgId { get; set; }
    public virtual List<Product> Products { get; set; }
    public virtual Organization Organization { get; set; }
}

1 个答案:

答案 0 :(得分:1)

我不知道我是否理解了你想要的东西,但是

var results = (from a in allCats.Where(x => x.Name == parentCatName)
               join b in allCats on a.CategoryId equals b.Parentcategory into children
               select new[] { a.CategoryId }.Concat(children.Select(z => z.CategoryId)))
              .SelectMany(x => x)
              .ToList();

我在Entity Framework 6.1.3上对其进行了测试,并为UNION ALL行正确生成select ...然后使用CROSS APPLY作为SelectMany }(???)