score:1

You could quite easily move the switch logic out into another function like so:

private static T GetReturnValue<T>(myClass x)
{
    switch (x)
    {
        case 1:
            return Math.Sqrt(x.Field1);
            break;
        case 2:
            return Math.Pow(x.Field2,
                            2);
            break;
        default:
            return x.Field3;
            break;
    }
}

And then you just need to pass your object to that function to get back the value you want:

var q = from x in myAnonymousTypeCollection
                    select new
                        {
                            ID = x.ID,
                            CalcField = GetReturnValue(x)
                        };

score:9

You could wrap your anonymous function as a (self-executing) Func<> delegate. This assumes you know the return type.

var q = from x in myAnonymousTypeCollection
    select new {
      ID = x.ID,
      CalcField = new Func<double>( () => { 
                    switch(x.SomeField) {
                      case 1:
                        return Math.Sqrt(x.Field1);
                      case 2:
                        return Math.Pow(x.Field2, 2);
                      default:
                        return x.Field3;
                    }
                  } )()
    };

score:13

First off, I usually prefer the method chain syntax over the query syntax for Linq. With that you can do this easily.

var q = myAnonymousTypeCollection
    .Select(x => 
            {
                object calcField; 

                 switch(x.SomeField) 
                 {
                      case 1:
                        calcField = Math.Sqrt(x.Field1);
                      case 2:
                        calcField =  Math.Pow(x.Field2, 2);
                      default:
                        calcField = x.Field3;

                 return new 
                        {
                            x.ID,
                            CalcField = calcField
                        };
            });

Without using method chains, you need either a method or an Func. Let's assume a Func

//replace these with actual types if you can.
Func<dynamic, dynamic> calculateField = 
    x => 
    {
        switch(x.SomeField) {
            case 1:
                return Math.Sqrt(x.Field1);
            case 2:
                return Math.Pow(x.Field2, 2);
            default:
                return x.Field3;
    }

var q = from x in myAnonymousTypeCollection
        select new { x.Id, CalcField = calculateField(x) };

Note: I didn't write this in an IDE, so please excuse any simple errors.

Here is the MSDN for dynamic. However, I have found that once you need to start passing anonymous types around, it is best to make an actual class.


Related Query

More Query from same tag