Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

Dynamic LINQ

Posted on 2008-10-09
3
760 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

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Occasionally there is a need to clean table columns, especially if you have inherited legacy data. There are obviously many ways to accomplish that, including elaborate UPDATE queries with anywhere from one to numerous REPLACE functions (even within…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…

856 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