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.
Source: stackoverflow.com
Related Query
- Syntax to execute code block inside Linq query?
- How to execute code as a part of the LINQ query
- LINQ - Query syntax vs method chains & lambda
- .NET LINQ query syntax vs method chain
- Calling a method inside a Linq query
- GroupBy with linq method syntax (not query syntax)
- LINQ Lambda vs Query Syntax Performance
- LINQ query to perform a projection, skipping or wrapping exceptions where source throws on IEnumerable.GetNext()
- How to Convert LINQ Comprehension Query Syntax to Method Syntax using Lambda
- AsNoTracking using LINQ Query syntax instead of Method syntax
- Syntax for linq query to List<string>
- Linq query to filter id inside a list of list c#
- LINQ - Method vs Query Syntax Difference
- LINQ Query Syntax to Lambda
- SQL Query to LINQ syntax using not exist and join
- Call class method inside the Linq Query
- Using Linq query inside List<T>.AddRange to conditionally add elements from one list to another
- Linq mix extension and query syntax
- MVC Razor brackets inside code block
- Is there any way to create a LINQ query as a variable without having the data source (yet)?
- C# multiple variables in lambda expression inside LinQ query
- Wrap a Linq query in a try/catch block using a method declaration
- Linq Query syntax vs. Method Chain: return type
- How does linq actually execute the code to retrieve data from the data source?
- Entity Framework: Update inside LINQ query
- Use dictionary inside linq query
- LINQ Source Code Available
- Call a method inside LINQ Query
- Convert EF LINQ method syntax to query syntax
- SQL ROW_NUMBER() in LINQ Query Syntax
More Query from same tag
- Pivot column entries into a comma separated list in a single row for distinct adjacent column?
- Converting a stored procedure output into Objects through LINQ
- linq query insert exist query string into linq query
- Display Average value from ViewModel in View
- LINQ DateTimeOffset comparison with today
- Left outer join errors
- Linq to XML - Get next element of sibling with specific value
- IEqualityComparer<T> does not work with List<T>.Distinct() method
- Extract Items from IEnumerable<ObservableCollection<T>> C#
- Get maximum value from Dictionary
- Error when accessing xml nodes
- Linq intersect to filter multiple criteria against list
- Trying to convert PIVOT SQL into LINQ lambda exp
- Return true from newly requested record created successfully by entity framework
- Select only members in anonymous with a certain attribute
- How to optimize this LINQ query for Visual Studio?
- Linq Query returning null parameters when selecting whole table
- Linq OrderBy - on duplicate values
- Mapping collections with LINQ
- LINQ Filtering a List of objects
- Sorting List based on another float List in C#
- Traverse list to add elements using .NET
- Removing elements in list that appear in dict
- Unable to cast object of type 'System.Collections.Generic.HashSet`1[libraryWebProject.Major]' to type 'libraryWebProject.Major'
- Convert Dictionary<string, Task<string>> to Dictionary<string, string>
- Avoid NullReferenceException in LINQ Expression on Datatable column
- LINQ Grouping by
- Comparing DateTime fields with different 'times'
- Ordering and concatenating two lists of different types
- ASP.Net Bootgrid Integration (without sorting)