繁体   English   中英

Linq从项目列表中获取项目列表

[英]Linq Get a list of items from a list of items

我有一个返回IQueryable<Criteria> Criteria可以具有多个Attribute而一个Attribute可以具有一个AttributeType

这是模型类:

public class Criteria
{
    public int Id { get; set; }
    public int CategoryId { get; set; }
    [Required] [MaxLength(100)] public string Name { get; set; }
    [MaxLength(1000)] public string Description { get; set; }
    public bool Highlight { get; set; }
    public int Order { get; set; }

    public IList<Attribute> Attributes { get; set; }
}

public class Attribute
{
    public int Id { get; set; }
    public int CriteriaId { get; set; }
    [Required] [MaxLength(100)] public string Name { get; set; }
    [MaxLength(100)] public string Description { get; set; }
    public int Order { get; set; }

    public AttributeType Type { get; set; }
    public AttributeOperation Operation { get; set; }
    public IList<Formula> Formulas { get; set; }
}

public class AttributeType
{
    public int Id { get; set; }
    public int AttributeId { get; set; }
    public string Name { get; set; }

    public Attribute Attribute { get; set; }
}

我的CriteriaService使用基本服务返回IQueryable<Criteria> 基本服务方法如下所示:

    /// <summary>
    ///     Gets all the entities
    /// </summary>
    /// <param name="includes">Option includes for eager loading</param>
    /// <returns></returns>
    public IQueryable<T> List(params string[] includes)
    {
        // Create a query
        IQueryable<T> query = _dbEntitySet;

        // For each include, append to our query
        if (includes != null) 
             foreach (var include in includes) 
                 query = query.Include(include);

        // Return our query
        return query;
    }

现在,我想返回给定类别的所有AttributeTypes 因此,我开始创建一个看起来像这样的方法:

public List<AttributeType> List(int categoryId)
{
    var query = _criteriaService.Value.List(categoryId, "attributes.type").Select(m => m.Attributes);
    // TODO: How to get a list of Types from the Attribute
    return new List<AttributeType>();
}

但我不确定我怎么可以得到所有的AttributeTypes每个Attribute

有人可以帮忙吗?

只需使用SelectMany将您的列表列表平化为一个列表:

var query = _criteriaService.Value.List(categoryId, "attributes.type")
    .SelectMany(m => m.Attributes)
    .Select(y => x.Type);

如上所述, SelectMany通常就是您想要的。

值得注意的是,最好使用尽可能多的Linq代码,因为IQueryable优于IEnumerable的通常用法是因为它可以在IEnumerable转换为其他类型的代码,例如SQL查询,因此不能一步一步完成进入C#内存。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM