Use LINQ Queries for Objects
To utilize the benefits of LINQ, it is integrated with NCache using the NCacheQuery class, which implements the IQueryable interface provided by the .NET framework. This integration allows the user to query objects using LINQ queries.
No code change is required for using LINQ queries aside from cache initialization and the previously mentioned interface implementation along with the expected new assembly reference and namespace additions. The rest of the code will work without any change in application.
LINQ Queries: Querying Objects through NCacheQuery class
You can use any of the following supported LINQ operators to retrieve NCache objects using NCacheQuery:
- Projection Operators
- Restriction Operators
- Basic Query Operators
- Logical Operators
- Aggregation Operators
- Wildcard Query Operators
Prerequisites to Use LINQ Queries
Bfore using LINQ queries ensure that following prerequisites are fulfilled:
- To learn about the standard prerequisites required to work with all NCache client-side features, please refer to the given page on Client-Side API Prerequisites.
- Indexing for searchable objects and their attributes need to be configured first as explained on our section on Dynamic Indexing and Configuring Query Indexes in the Administrator's Guide.
- For API details, refer to: NCacheQuery.
LINQ Operations
The following code uses the NCacheQuery class to demonstrate several operators we've discussed and illustrate how to use NCache with LINQ.
Using Query Expression
// Precondition: Cache is already connected
// Create custom class LINQ object
IQueryable<Product> products = new NCacheQuery<Product>(cache);
// LINQ query to search cache
IQueryable<Product> result = from prod in products where (prod.Category == "Beverages" || prod.Category == "Dairy") && prod.UnitsInStock > 10 select prod;
if (result != null)
{
foreach (Product product in result)
{
Console.WriteLine($"Product '{product.ProductName}' in Category '{product.Category}' has stock of '{product.UnitsInStock}' units");
}
}
else
{
Console.WriteLine($"No product found");
}
Using Lambda Expression
// Lambda expression for same query
IQueryable<Product> result = products.Select(prod => prod).Where(prod => ((prod.Category == "Beverages" || prod.Category == "Dairy") && prod.UnitsInStock > 10));
Additional Resources
NCache provides sample application for NCache LINQ on GitHub.
See Also
.NET: Alachisoft.NCache.Linq namespace.