c#LINQ OrderBy、动态对象和空值

c#LINQ OrderBy、动态对象和空值,c#,linq,sql-order-by,expression,C#,Linq,Sql Order By,Expression,我正在尝试生成一个动态表达式,可以对ExpandoObjects列表进行排序。我不知道expandoobjects中会有什么(string、int、decimal、datetime等) 不幸的是,如果在执行orderby时列表中有空值,则会引发异常。在使用Where方法进行排序之前,我可以从集合中删除空值,但我希望在返回的结果中保留空行 我想做的是生成一个If-Else语句,类似于: x => x.Item["Key"] != null ? x.Item["Key] : defaultva

我正在尝试生成一个动态表达式,可以对ExpandoObjects列表进行排序。我不知道expandoobjects中会有什么(string、int、decimal、datetime等)

不幸的是,如果在执行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(type==typeof(ExpandoObject))
{
arg=表达式参数(类型(T),“x”);
expr=arg;//获取T的类型
var first=(IDictionary)source.first();
//将字符串的大小写与正确的键值匹配。
固有值=
first.Keys.first(x=>String.Equals(x,prop,StringComparison.CurrentCultureIgnoreCase));
var key=Expression.Constant(propval,typeof(string));
ParameterExpression dictExpr=表达式.参数(typeof(IDictionary));
var indexer=dictExpr.Type.GetProperty(“项”);
var exprkeyed=Expression.Property(expr,indexer,key);
//生成x.Item[“KeyString”]以便我可以访问该对象。
expr=exprkeyed;
var Null=表达式常数(Null);
expr=Expression.NotEqual(expr,Null);
expr=Expression.Condition(expr,exprkeyed,Expression.Constant(false));//作为else返回什么?
类型=类型(对象);
}
不幸的是,如果我尝试根据键类型设置默认值,我会得到一个异常,来自if/else的返回值不匹配(即:一个是system.object,一个是system.datetime)。我认为object的默认值也是null,所以这不是最好的

有没有一种方法可以在不使用where语句的情况下首先删除空条目?也许我可以在另一个页面上返回一些东西,比如跳绳或低/高


谢谢您的时间。

您将返回一个
表达式。默认值(typeof(T))
。 在你的代码中你改变了

expr = Expression.Condition(expr, exprkeyed, Expression.Default(typeof(T)));