Sze*_*zer 5 c# linq entity-framework
我有一个查询,应该这样订购:
var list = new List<MonthClosureViewModel>();
var orderedList = list
.OrderByDescending(x => x.Project)
.ThenByDescending(x => x.ChargeLine)
.ThenByDescending(x => x.DomesticSite) //<- x.DomesticSite might be null sometimes
.ThenByDescending(x => x.ChargeSite) //<- x.ChargeSite might be null sometimes
.ThenByDescending(x => x.RateGroup)
.ThenByDescending(x => x.ApprovedHrs)
.ThenByDescending(x => x.NotApprovedHrs);
public class MonthClosureViewModel
{
public Project Project { get; set; }
public ChargeLine ChargeLine { get; set; }
public Site DomesticSite { get; set; }
public Site ChargeSite { get; set; }
public RateGroup RateGroup { get; set; }
public decimal Rate { get; set; }
public decimal ApprovedHrs { get; set; }
public decimal NotApprovedHrs { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
但是如果任何对象为null(完全按设计),则此查询失败.如果object为null,我如何在结尾处放置空值或跳过排序?
添加:
@ LasseV.Karlsen提到我可能有另一个问题.我真的得到了ArgumentNullException,但原因并不在于某些对象null(我在调试器中看到它并错误地认为这是我的问题).真正的原因是@RaphaëlAlthaus提到我没有IComparable<>在我的任何课程中实施MonthClosureViewModel......
在我完成它之后,一切都开始按预期工作,即使对象是 null
您尝试按复杂的属性进行排序,这是(正如您提到的)真正的问题。
为了使其成为可能,您必须
IComparable<T>在你的课堂上实施
使用 OrderBy / OrderByDescending 的其他重载,它们也采用 asIComparer<TKey>参数(msdn中的 OrderBy 重载)
在 order by 子句中使用复杂属性的简单属性(带有 null 检查。在这种情况下,必须进行 null 检查以避免空引用异常):
例如 :
.OrderByDescending(x => x.Project == null ? string.Empty : x.Project.Name)
Run Code Online (Sandbox Code Playgroud)