我需要将参数传递给linq查询。我的疑问如下:
var appointments = (from a in inMemContext.Appointments
join u in inMemContext.Users on a.UserId equals u.UserId into AppointmentAssignments
from aa in AppointmentAssignments.DefaultIfEmpty()
join l in inMemContext.Languages on a.PreferredLanguage equals l.LanguageKey
where a.BranchId == branchId
&& a.AppointmentDate.Date == TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById(b.TimeZoneId)).Date
orderby a.AppointmentTime
select new AppointmentEntryDetailsDto
{
Id = a.AppointmentId.ToString(),
StartTime = (a.AppointmentTime).ToString("hh:mm tt", CultureInfo.InvariantCulture),
AppointmentType = a.AppointmentType.AppointmentTypeName,
});在上面的查询中,我使用的是按AppointmentTime排序的数据。现在我需要将动态排序值设置为升序或降序。
对于此行:
orderby a.AppointmentTime [OrderParameter]升序或降序。我该怎么做呢?
发布于 2020-07-31 14:15:08
没有这样的内置方式。
您可以创建自定义扩展方法(从而不使用语言集成查询),或分支整个语句,或按负时间排序(排序前根据参数转换时间,从24:00:00减去或类似)。
发布于 2020-07-31 14:59:57
这可以通过创建一个扩展方法来实现,该方法可以动态地改变它是升序还是降序:
public static class LinqExtensions
{
public static IEnumerable<TModel> OrderByDynamic<TModel, TKey>(this IEnumerable<TModel> source, Func<TModel, TKey> selector, bool ascending = true)
{
if (ascending) return source.OrderBy(selector);
return source.OrderByDescending(selector);
}
}使用:
var appointmentList = new List<Appointment>
{
new Appointment { UserId = "1", PreferredLanguage = "English", BranchId = "1", AppointmentDateTime = new DateTime(2000, 1, 1, 0, 0, 0) },
new Appointment { UserId = "2", PreferredLanguage = "Japanese", BranchId = "1", AppointmentDateTime = new DateTime(2000, 2, 1, 0, 0, 0) },
new Appointment { UserId = "3", PreferredLanguage = "Spanish", BranchId = "2", AppointmentDateTime = new DateTime(2000, 3, 1, 0, 0, 0) },
};
// Order By Descending
var appointments = appointmentList.OrderByDynamic(selector: x => x.AppointmentDateTime, ascending: false);这与Linq查询不直接兼容,但可以用于任何IEnumerable的结果。我将把如何在您的特定情况下使用它留给您。
https://stackoverflow.com/questions/63186215
复制相似问题