Solved

Dynamic LINQ

Posted on 2008-10-09
3
761 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
[X]
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
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

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

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 article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled

726 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