简体   繁体   English

如何使用Orderby创建动态linq查询?

[英]How to use Orderby for creating dynamic linq queries?

I have linq query which is as follows 我有linq查询,如下所示

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. 但我想基于sortby变量值以不同的顺序排序。 How can i do that using Linq? 我怎么能用Linq做到这一点?

Using reflection: 使用反射:

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);

For sample class: 对于样本类:

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

    public string field2 { get; set; }

    public string field3 { get; set; }
}

You can do it this way: 你可以这样做:

var index = 1;

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

But as fields have different types you have to do some type cast as you see l.field1.ToString() 但是因为字段有不同的类型,你必须做一些类型转换,如你所见l.field1.ToString()

Way you do it using lambda is: 使用lambda的方法是:

var sortedList =
    list.OrderBy(l => 
            index == 1 ? l.field1.ToString() 
            : index == 2 ? l.field2 
            : l.field3)
        .Select(l => l).ToList();

If you use the OrderBy() LINQ extension method, you can pass in a predicate which could be something like (untested): 如果使用OrderBy()LINQ扩展方法,则可以传入一个类似(未经测试)的谓词:

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

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

var oSortedList = oResultList.OrderBy( orderByClause );

I'm sure the syntax if way off, but I have done something like this before... 我确定语法如果关闭,但我之前做过类似的事情......

Hope this helps! 希望这可以帮助!

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM