Solved

Dynamic LINQ

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

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
C# Desktop Application 3 29
Count with a subquery showing details 10 41
sql server concatenate fields 10 31
Find results from sql within a time span 11 29
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…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
This Micro Tutorial hows how you can integrate  Mac OSX to a Windows Active Directory Domain. Apple has made it easy to allow users to bind their macs to a windows domain with relative ease. The following video show how to bind OSX Mavericks to …
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…

813 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

15 Experts available now in Live!

Get 1:1 Help Now