首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Linq从项目列表中获取项目列表

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

Stack Overflow用户
提问于 2018-06-24 22:19:44
回答 2查看 123关注 0票数 0

我有一个返回IQueryable<Criteria>的服务。Criteria可以有多个Attribute,一个Attribute可以有一个AttributeType

以下是模型类:

代码语言:javascript
复制
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>。基本服务方法如下所示:

代码语言:javascript
复制
    /// <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。所以我已经开始创建一个如下所示的方法:

代码语言:javascript
复制
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>();
}

但我不确定如何才能获得每个Attribute的所有AttributeTypes

有人能帮帮忙吗?

EN

回答 2

Stack Overflow用户

发布于 2018-06-24 22:31:22

只需使用SelectMany,它会将列表列表展平为单个列表:

代码语言:javascript
复制
var query = _criteriaService.Value.List(categoryId, "attributes.type")
    .SelectMany(m => m.Attributes)
    .Select(y => x.Type);
票数 1
EN

Stack Overflow用户

发布于 2018-06-24 22:41:46

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

值得注意的是,您最好尽可能多地使用Linq代码,因为通常在IEnumerable上使用IQueryable是因为它会在幕后转换成某种其他类型的代码,比如SQL查询,因此不会在C#内存中一步一步地完成。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51010768

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档