Mediator
Mediator

Reputation: 15378

LINQ Query - how order by?

In debug i get

m_tableContext.TemplateTables.OrderBy(a => a.id) Expression cannot contain lambda expressions

private readonly TamplateTableContext m_tableContext = new TamplateTableContext();

m_tableContext.Load(m_tableContext.GetTemplateTableQuery());    

lbTemplateTable.DataContext = m_tableContext.TemplateTables.OrderBy(a => a.id);

How do sort ?

Upvotes: 2

Views: 1344

Answers (3)

DaveShaw
DaveShaw

Reputation: 52808

You cannot inspect Lambda expressions at runtime. They need to be compiled, even changing a method containing a lambda (not just the lambda itself) at runtime requires recompilation.

Upvotes: 1

ecathell
ecathell

Reputation: 1030

if that is one method call, it wont work. Silverlight calls are asynchronous you have to provide a callback for the Load method so that when its done it dumps to a new method....

private readonly TamplateTableContext m_tableContext = new TamplateTableContext();

m_tableContext.Load(m_tableContext.GetTemplateTableQuery(),onLoadOperationCompleted);    


public void onLoadOperationCompleted(LoadOperation<TemplateTable> lo)
        {
            if (!lo.HasError)
            {
               lbTemplateTable.DataContext = 
                  new ObservableCollection<TemplateTable>(lo.Entities.OrderBy(a => a.id));
            }
}

Its a contrived example. I use MVVMLight and a ServiceLocator pattern, so what I am showing you isnt really in context because it looks like you may actually be doing it all in code behind...but I was really just trying to show you how to do the callback.

Upvotes: 0

DK.
DK.

Reputation: 3243

it's a bit hard to tell by the current code. Example below uses the same OrderBy expression, and it compiles and runs ok.

public class A { public int ID; }

public static void Test()
{
    List<A> listA = new List<A> {new A {ID=7}, new A {ID=2}, new A {ID=16}};

    var query1 = from x in listA orderby x.ID select x;
    var query2 = (from x in listA select x).OrderBy(a => a.ID);

    foreach(var x1 in query1) Console.WriteLine("{0}", x1.ID);
    foreach(var x2 in query2) Console.WriteLine("{0}", x2.ID);
}

Error you have might actually come from insufficient information about key data type. This discussion might help you with it.

Update: Ah, it's in debug, as in debug mode, not DEBUG target, is it ?!... If you are trying to see the result in quick watch or immediate window - it's expected error. This doesn't mean that there is something wrong with the code, just that debugger doesn't like lambda expressions.

Upvotes: 2

Related Questions