There is another option.
Let’s assume there is a task to load some data using DA LINQ into an anonymous class. The catch is that the where part of the data query might differ based on some user input. Different fields can be used there, one or more conditions can be omitted etc.
It is not possible to predefine a variable for the query result because the result type is anonymous and thus cannot be referenced in code.
Also there is no way to conditionally define different conditions in the where part of the query itself.
he solution is to decompose the LINQ query.
In .NET any LINQ query is actually a chain of method calls hidden behind a fancy syntax. It is possible to write any LINQ query using these method calls only. There is no performance hit as this is actually exactly the same code
So take a look at this code:
method LoadData(foo: Boolean);
// Define the data source (in this case - remote data table accessed via DA LINQ)
var query := fDataModule.DataAdapter.GetTable<Customers>().AsQueryable();
// Add different conditions based on method parameter
if foo then begin
query := query.Where(c -> c.Name.StartsWith('A'));
query := query.Where(c -> c.Discount > 0);
// Put the data into an anonymous class
var query1 := query.Select(c -> new class(ID := c.Id, ADDR := c.Address));
// Load data
var data := query1.ToList();
// Debug output
System.Windows.Forms.MessageBox.Show('Data type: ' + data.GetType().ToString() + #13#10 + 'Data count: ' + data.Count.ToString());
Using this approach it is possible to add different conditions to the query at runtime.