我有一个返回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>();
}
但我不确定如何才能获得每个Attribute
的所有AttributeTypes
。
有人能帮帮忙吗?
发布于 2018-06-24 22:31:22
只需使用SelectMany
,它会将列表列表展平为单个列表:
var query = _criteriaService.Value.List(categoryId, "attributes.type")
.SelectMany(m => m.Attributes)
.Select(y => x.Type);
发布于 2018-06-24 22:41:46
如上所述,SelectMany
通常是您想要的。
值得注意的是,您最好尽可能多地使用Linq代码,因为通常在IEnumerable
上使用IQueryable
是因为它会在幕后转换成某种其他类型的代码,比如SQL查询,因此不会在C#内存中一步一步地完成。
https://stackoverflow.com/questions/51010768
复制相似问题