Solved

Dynamic LINQ

Posted on 2008-10-09
3
750 Views
Last Modified: 2013-11-11
Hi!

I know there is way to build linq dynamicalli with Expression class and i was struggling for hours to make following code dynamic:

public IQueryable<T> OrderByGuid<T>(IQueryable<T> query, string fieldName) where T : Ii18n
        {
            switch (fieldName)
            {
                case "X":
                    return query.OrderBy(x => x.i18ns.SingleOrDefault(
y => y.LanguageID == CurrentLanguageID && y.ValueID == x.X).Value);
                /**
                .
                .
                .
                etc.
                **/
            }
            return null;
        }

The idea is that i have lists that contain language-dependent columns and when i order by that column, I want it to be ordered by the value of current language.

Regards
Max
0
Comment
Question by:maxlego
3 Comments
 
LVL 4

Accepted Solution

by:
novynov earned 500 total points
ID: 22689714
Have you looked at LinqKit (http://www.albahari.com/nutshell/linqkit.aspx) or the work of Tomas Petricek (http://tomasp.net). Both places give good coverage of approaches to dynamic queries using Expression building. They both also provide some extensions (i.e. code) that make the job much easier. If I'm not mistaken, the tools in LinqKit are based on the work of Mr. Petricek, but are slightly newer and modified.

Now, I may not be understanding your needs exactly, but consider this: Most of the time, dynamic queries are only required if you don't know the whole set of possible fields that the query may be based on beforehand. In other words, if I know that my query may be ordered by FieldX or FieldY and nothing else, I can do this without dynamic Linq. I just need to build my query (which is lazily evaluated) as such:

var q = context.Table.Where(t => t.Filtercondition == true);
if (SomeCondition == true)
{
   q = q.OrderBy(t => t.FieldX);

}
else
{
   q = q.OrderBy(t -> t.FieldY);
}

Linq will happily build up the expression tree for you in this incremental fashion. Even if I have multiple possible fields for my orderby (to use your example), I could just change my logic to do OrderBy for the first one, and ThenBy for the rest. When it comes to Where expressions, I can combine these incrementally - as long as they are to be combined in a logical AND fashion. If not, I can use something like PredicateBuilder (included in LinqKit) to build up a predicate expression using arbitrary combinations of AND and OR.

So unless I'm not understanding your problem or what you mean by dynamic linq, if I know that I'm going to have a current language value come into the query, and that each language maps to one column that I need to do an orderby on, then I just need some switch statement logic to build the correct orderby expression. Something like the code snippet below would seem to work:

I hope this helps. If not, let me know....and I'll see if I can help more.





using System.Linq.Expressions;
 

Expression<Func<Entity, string>> orderByFunc = (e => e.EnglishField); //default
 

switch (language)

{

   case "en-US":

      break;

   case "en-NZ":

       break;

   case "fr-be":

      orderByFunc = (e => e.FrenchField);

      break;

  case "de-at"

      orderByFunc = (e => e.GermanField);

      break;

  default:

    break;

}
 

q = q.Entities.Where(e => e.SomeCondition).OrderBy(orderByFunc);

Open in new window

0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Wpf develop 5 32
Long URL in SMS 6 24
c# if statement weird reaction 3 29
Open a word document 23 13
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
This video discusses moving either the default database or any database to a new volume.
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now