【发布时间】:2014-05-05 23:24:17
【问题描述】:
我正在尝试生成一个可以对 ExpandoObjects 列表进行排序的动态表达式。我不知道 expandoobjects 中的内容(字符串、整数、小数、日期时间等)。
不幸的是,如果在进行 orderby 时列表中有空值,则会引发异常。在使用 Where 方法进行排序之前,我可以从集合中删除空值,但我想在返回的结果中保留空行。
我试图做的是生成一个 If Else 语句,例如:
x => x.Item["Key"] != null ? x.Item["Key] : defaultvaluefortype
这是我的代码 sn-p:
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);
}
不幸的是,如果我尝试根据键类型设置默认值,我会得到一个异常,即我的 if/else 的返回值不匹配(即,一个是 system.object,一个是 system.datetime) .我相信 object 的默认值也是 null ,所以这不是最好的。
有没有办法在不使用 where 语句首先删除空条目的情况下做到这一点?也许我可以在 else 上返回一些东西,比如跳过或排序低/高?
感谢您的宝贵时间。
【问题讨论】:
标签: c# linq sql-order-by expression