[英]c# LINQ OrderBy, dynamic objects, and null values
I'm attempting to generate a dynamic expression that can order a list of ExpandoObjects. 我正在尝试生成可以对ExpandoObjects列表进行排序的动态表达式。 I don't know what will be in the expandoobjects (string, int, decimal, datetime, etc).
我不知道expando对象中的内容(字符串,整数,十进制,日期时间等)。
Unfortunately, it appears that if a null value is in the list when doing an orderby, an exception is thrown. 不幸的是,似乎在执行orderby时如果列表中为空值,则会引发异常。 I could remove the null values from my collection prior to sorting with a Where method, but I want to keep the null rows in the results returned.
我可以在使用Where方法排序之前从集合中删除null值,但是我想在返回的结果中保留null行。
What I was trying to do was generate an If Else statement, something like: 我试图做的是生成If Else语句,例如:
x => x.Item["Key"] != null ? x.Item["Key] : defaultvaluefortype
Here's my code snippet: 这是我的代码段:
if (type == typeof (ExpandoObject))
{
arg = Expression.Parameter(typeof (T), "x");
expr = arg; //Get type of T
var first = (IDictionary<string, object>) source.First();
//Match the case of the string to the correct key value.
var propval =
first.Keys.First(x => String.Equals(x, prop, StringComparison.CurrentCultureIgnoreCase));
var key = Expression.Constant(propval, typeof(string));
ParameterExpression dictExpr = Expression.Parameter(typeof(IDictionary<string, object>));
var indexer = dictExpr.Type.GetProperty("Item");
var exprkeyed = Expression.Property(expr, indexer, key);
//Generates x.Item["KeyString"] so I can access the object.
expr = exprkeyed;
var Null = Expression.Constant(null);
expr = Expression.NotEqual(expr, Null);
expr = Expression.Condition(expr, exprkeyed, Expression.Constant(false)); //what do I return as the else?
type = typeof(Object);
}
Unfortunately, if I try to set a default based on the key type, I get an exception that the return values from my if/else don't match (ie; one is system.object, one is system.datetime). 不幸的是,如果我尝试根据密钥类型设置默认值,则会出现一个异常,即我的if / else返回值不匹配(即,一个是system.object,一个是system.datetime)。 I believe the default value for object is null as well, so that's not the best.
我相信object的默认值也为null,所以这不是最好的。
Is there a way to do this without using a where statement to remove the null entries first? 有没有一种方法,而无需使用where语句先删除空条目? Maybe something I could return on the else that's like a skip or a sortlow/high?
也许我可以返回其他的东西,例如跳过或排序低/高?
Thanks for your time. 谢谢你的时间。
You would return a Expression.Default(typeof(T))
. 您将返回一个
Expression.Default(typeof(T))
。 In your code you change 在您的代码中,您进行更改
expr = Expression.Condition(expr, exprkeyed, Expression.Default(typeof(T)));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.