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.