C#LINQ:扩展Include以将其转换为list并添加OrderBy
我计划对.Include()函数进行扩展。 目前,我一直在使用这样的东西:C#LINQ:扩展Include以将其转换为list并添加OrderBy,c#,linq,C#,Linq,我计划对.Include()函数进行扩展。 目前,我一直在使用这样的东西: var data = _context.Examples .Include(example => examples.SubExamples) .FirstOrDefault(); if (data == null) return null; data.SubExamples = data.SubExamples .OrderBy(subExamples => subExamp
var data = _context.Examples
.Include(example => examples.SubExamples)
.FirstOrDefault();
if (data == null)
return null;
data.SubExamples = data.SubExamples
.OrderBy(subExamples => subExamples.CreatedOn)
.ToList();
return data;
我需要通过CreatedOn对“SubExample”进行排序,并将其转换为ToList(),以便自动映射器可以毫无问题地映射它。因为我将在不同的实体上多次使用相同的方法,所以我计划对Include进行扩展。但我对如何重新分配列表有意见
public static IQueryable<TEntity> IncludeOrderBy<TEntity, TProperty>(
this IQueryable<TEntity> query,
Expression<Func<TEntity, TProperty>> include,
params Expression<Func<TEntity, TProperty>>[] orders)
{
query.Include(include);
// Need to assign to the Property as List() and Apply the OrderBy
return query;
}
公共静态iquiryable IncludeOrderBy(
这是一个易懂的问题,
表达方式包括:,
参数表达式[]顺序)
{
查询.包含(Include);
//需要将属性指定为List()并应用OrderBy
返回查询;
}
问题是如何将它们重新分配回列表并添加订单?尝试以下操作:
return context.Examples
.Include(example => examples.SubExamples)
.FirstOrDefault()
?.SubExamples
.OrderBy(subExamples => subExamples.CreatedOn)
.ToList();
我不知道你为什么需要params来下订单,但也许这个可以解决你的问题
public static IQueryable<T> IncludeOrderBy(this IQueryable<T> query,
Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null, params Expression<Func<T, object>>[] includes)
{
includes.ForEach(x => query = query.Include(x));
if (orderBy != null)
{
query = orderBy(query);
}
return query;
}
当您使用它时,您可以进行排序,或者您有一个包含父项和子项的类,您可以分配它们并返回它们。你的代码真的会变得如此短和易于使用以至于所有这些都是值得的吗?你可能应该使用
ProjectTo
,然后不需要Include
。排序字段名是否总是“CreatedOn”?我的意思是为什么你需要发送PARAMATER“PARAMS表达式”命令?考虑改进你的答案。MickeyD,除非它是SQL查询,在这种情况下,我们将编写整个内容:d这个答案不正确;它仅在OP实际需要这些项和子项,并且希望子项已经由某个事物排序,并且希望将其作为扩展方法时返回子项。答案应该是关于这些事情的,或者清楚地解释为什么他们不提供它们,并鼓励采用不同的编码方式来解决问题。我制定了顺序参数,这样我就可以进行多次排序。我将使用.OrderBy().ThenBy()。但这不是问题的重点,我的问题是如何重新分配已排序的数据。您尝试过使用它吗?IncludeOrderBy(x=>x.OrderBy(y=>y.CreatedOn)。然后by(z=>z.Creator));谢谢你的回答,是的,我测试过了,但没有给出我想要的结果
list.IncludeOrderBy(x => x.OrderBy(y => y.CreatedOn));