[英]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.