c# – LINQ选择包含字符串的所有子集合的所有项目

我正在使用
jqueryui自动完成功能来帮助用户选择项目.我无法从对象的子集合中选择正确的项目.

对象结构(简化)是

public class TargetType
{
    public int Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<SubCategory> SubCategories { get; set; }

    public TargetType()
    {
        SubCategories = new HashSet<SubCategory>();
    }
}

public class SubCategory
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<SubTargetType> SubTargetTypes { get; set; }

    public SubCategory()
    {
        SubTargetTypes = new HashSet<SubTargetType>();
    }
}

目前我正在使用嵌套的foreach循环,但有更好的方法吗?
当前代码:

List<SubTargetResponse> result = new List<SubTargetResponse>();
foreach (SubCategory sc in myTargetType.SubCategories)
{
    foreach (SubTargetType stt in sc.SubTargetTypes)
    {
        if (stt.Name.ToLower().Contains(type.ToLower()))
        {
            result.Add(new SubTargetResponse {
                Id = stt.Id,
                CategoryId = sc.Id,
                Name = stt.Name });
        }
    }
}

最佳答案 你可以像这样使用Linq

var result = myTargetType.SubCategories
                         .SelectMany(sc => sc.SubTargetTypes)
                         .Where(stt => stt.Name.ToLower().Contains(type.ToLower()))
                         .Select(stt => new SubTargetResponse {
                                        Id = stt.Id,
                                        CategoryId = sc.Id,
                                        Name = stt.Name });

以上查询不起作用.以下应该可行,但我不建议这样做,因为它不会更快或更易读.

var result = myTargetType.SubCategories
                         .Select(sc => new Tuple<int, IEnumerable<SubTargetType>>
                                            (sc.Id, 
                                             sc.SubTargetTypes.Where(stt => stt.Name.ToLower().Contains(type.ToLower()))))
                         .SelectMany(tpl => tpl.Item2.Select(stt => new SubTargetResponse {
                                        Id = stt.Id,
                                        CategoryId = tpl.Item1,
                                        Name = stt.Name }));
点赞