tags:

views:

45

answers:

3

I wrote a method which calls a method that returns a linq query. Inside this method, I need to apply a case expression to the linq query I'm receiving from the method I call. I thought that maybe with a lambda expression it would be possible to apply a case expression, but how can I do this?

A: 

Well, you can use a statement body lambda expression:

Func<int,string> x = value =>
{
    switch(value)
    {
        case 0: return "hello";
        case 1: return "there";
        default: return "other";
    }
};

However, you won't be able to convert that into an expression tree, as they only support lambda expressions with a single expression. Are you trying to use LINQ to SQL here?

Of course, you could use nested conditionals instead, and that should work with expression trees:

Expression<Func<int,string>> x = value =>
    value == 0 ? "hello"
    : value == 1 ? "there"
    : "other";

It's a sort of switch/case... although not terribly efficient, it might be good enough for you.

Jon Skeet
Yes, I'm trying to use LINQ to SQL here. And one of the requirements is speed. The application I'm working on is rather fast in almost all of its tasks and I can't drop the quality, if you know what I mean.
Hallaghan
@Hallaghan: Well it's not efficient in *C#* but it might translate to the appropriate SQL without any problems. I'd find something that works first, and *then* worry about the efficiency.
Jon Skeet
A: 

You might be able to use the ternary statement.

[boolean expression] ? [result if true] : [result if false]
Meiscooldude
I tried doing it that way but only got an exception.var c = q.Where(e => e.Status.Value == 6 ? e.Status.Value = 0 : e.Status.Value);
Hallaghan
@Hallaghan: "Only got an exception" isn't terribly detailed. Please provide as much information as possible in the question. If you've tried something but received an exception, tell us all about it. Likewise it would have helped if you'd said you were using LINQ to SQL to start with.
Jon Skeet
I'm sorry, I'm having a bad day and I'm kind of distracted.On topic, I get a System.InvalidOperation exception, when trying to convert from type bool to int. I wonder if it's happening because e.Status is a nullable.
Hallaghan
+1  A: 

Can you use a plain old function to accomplish this instead of a lambda?

X.Select( GetY );

or

X.Select( x => GetY(x) );

or

from x in X
select new
{
   y = GetY(x)
};

...

private YType GetY( XType x )
{
    switch( x )
    {
       ...
    }
}
Jerod Houghtelling
Thanks Jerod, I'll go with your solution.
Hallaghan