Initialization Expression
An initialization expression initializes a new object. The following types can be initialized and returned by a LINQ query:
- A collection of zero or more typed objects or a projection of complex types in the model.
- CLR types.
- Anonymous types.
An anonymous type initialization is shown in the following example in query expression syntax:
using ( FluentModel dbContext = new FluentModel() )
{
var query = from product in dbContext.Products
where product.UnitPrice > 30
select new
{
Name = product.ProductName,
Price = product.UnitPrice
};
foreach ( var item in query )
{
Console.WriteLine( "Name: {0}, Price: {1}", item.Name, item.Price );
}
}
Using dbContext As New FluentModel()
Dim query = From product In dbContext.Products
Where product.UnitPrice > 30
Select New With {Key .Name = product.ProductName, Key .Price = product.UnitPrice}
For Each item In query
Console.WriteLine("Name: {0}, Price: {1}", item.Name, item.Price)
Next item
End Using
The following example in method-based query syntax shows anonymous type initialization:
using ( FluentModel dbContext = new FluentModel() )
{
var query = dbContext.Products.Where( p => p.UnitPrice > 30 ).Select(
p => new
{
Name = p.ProductName,
Price = p.UnitPrice
} );
foreach ( var item in query )
{
Console.WriteLine( "Name: {0}, Price: {1}", item.Name, item.Price );
}
}
Using dbContext As New FluentModel()
Dim query = dbContext.Products.Where(Function(p) p.UnitPrice > 30).Select(Function(p) _
New With _
{ _
Key .Name = p.ProductName, _
Key .Price = p.UnitPrice _
})
For Each item In query
Console.WriteLine("Name: {0}, Price: {1}", item.Name, item.Price)
Next item
End Using
User-defined class initialization is also supported. The following example in query expression syntax shows a custom class being initialized in the query:
public class MyProduct
{
public string Name
{
get;
set;
}
public decimal Price
{
get;
set;
}
}
Public Class MyProduct
Public Property Name() As String
Public Property Price() As Decimal
End Class
using ( FluentModel dbContext = new FluentModel() )
{
var query = dbContext.Products.Where( p => p.UnitPrice > 30 ).Select(
p => new MyProduct
{
Name = p.ProductName,
Price = p.UnitPrice
} );
foreach ( var item in query )
{
Console.WriteLine( "Name: {0}, Price: {1}", item.Name, item.Price );
}
}
Using dbContext As New FluentModel()
Dim query = dbContext.Products.Where(Function(p) p.UnitPrice > 30).Select(Function(p) _
New MyProduct With _
{ _
.Name = p.ProductName, _
.Price = p.UnitPrice _
})
For Each item In query
Console.WriteLine("Name: {0}, Price: {1}", item.Name, item.Price)
Next item
End Using