1
我试图生成一个动态表达式,可以命令一个ExpandoObjects的列表。我不知道什么是expandoobjects(string,int,decimal,datetime等)。c#LINQ OrderBy,动态对象和空值
不幸的是,如果在执行orderby时列表中出现空值,则会抛出异常。在使用Where方法排序之前,我可以从集合中删除空值,但是我希望返回结果中的空行。
什么,我试图做的是产生的if else语句,是这样的:
x => x.Item["Key"] != null ? x.Item["Key] : defaultvaluefortype
这里是我的代码片段:
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)。我相信对象的默认值也是null,所以这不是最好的。
有没有办法做到这一点,而不使用where语句先删除空条目?也许我可以在其他东西上返回,就像跳过或分拣/高?
谢谢你的时间。