4

I have linq query which is as follows

string sortby="Date"; //it can be name or something else as well

var query=(from t in Uow.Transactions.GetAllWithReferences()
           orderby t.Date descending
           select t);

But I want to orderby differently based on sortby variable value. How can i do that using Linq?

4

4 回答 4

1

使用反射:

string sortby="Date" //it can be name or something else as well

var query=(from t in Uow.Transactions.GetAllWithReferences()
           orderby t.GetType().GetProperty(sortby).GetValue(t, null) descending
           select t);
于 2013-03-14T13:00:17.187 回答
1

如果您使用 OrderBy() LINQ 扩展方法,您可以传入一个谓词,它可能类似于(未经测试):

Predicate orderByClause;
if ( blah == "date" )
    orderByClause = { order => order.Date };

if ( blah == "something else" ) 
    orderByClause = { order => order.SomethingElse };

var oSortedList = oResultList.OrderBy( orderByClause );

我确定语法是否可行,但我之前做过类似的事情......

希望这可以帮助!

于 2013-03-14T13:05:38.303 回答
1

对于示例类:

private class Tst
{
    public int field1 { get; set; }

    public string field2 { get; set; }

    public string field3 { get; set; }
}

你可以这样做:

var index = 1;

var sortedList = (from l in list
                  orderby index == 1 ? l.field1.ToString() : index == 2 ? l.field2 : l.field3  
                  select l);

但是由于字段具有不同的类型,您必须进行一些类型转换,如您所见l.field1.ToString()

使用 lambda 的方法是:

var sortedList =
    list.OrderBy(l => 
            index == 1 ? l.field1.ToString() 
            : index == 2 ? l.field2 
            : l.field3)
        .Select(l => l).ToList();
于 2013-03-14T13:02:40.017 回答
1

你可以使用一个库,这是我最喜欢的一个:http: //dynamite.codeplex.com/

于 2013-03-14T13:08:36.760 回答