SmallToolsIUse.Linq.Extensions
Posted on by Cosmin Vana
SmallToolsIUse.Linq.Extensions 1.0.0
A set of Linq extension methods which can be used to solve common scenarios in .NET Applications. The package is available on Nuget: https://www.nuget.org/packages/SmallToolsIUse.Linq.Extensions/
In order to use the extension methods, add the following using statement:
using SmallToolsIUse.Linq.Extensions;
IEnumerable Extensions
Check if an instance which implementes IEnumerable is null or empty:
if(!customers.IsNullOrEmpty())
{
// do something with customers
}
Compare two IEnumerable of different types (e.g. DTO from your API and entities from your database):
var customersToUpdate = customersDto.In(customersFromDb, c => c.Id, c => c.Id)
var customersToDelete = customersFromDb.NotIn(customersDto, c => c.Id, c => c.Id)
var customersToInsert = customersDto.NotIn(customersFromDb, c => c.Id, c => c.Id)
Note: If both collections have the same type, you need to specify a single key selector.
IQueryable Extensions
Add sorting to your IQueryable using the field name.
Without extensions:
// assume we have sortBy field as a string, as it may be the case if it's captured from the query string.
var myCustomers = dbContext.Customers.Select(c => new CustomerDto());
if(sortBy == "FirstName")
{
myCustomers = myCustomers.OrderBy(c => c.FirstName); // also, need to check if it's descending or not
}
else if(sortBy == "LastName"
{
myCustomers = myCustomers.OrderBy(c => c.LastName); // also, need to check if it's descending or not
}
With linq extensions:
// assume we have sortBy field as a string, as it may be the case if it's captured from the query string.
var myCustomers = dbContext.Customers.Select(c => new CustomerDto());
myCustomers = myCustomers.OrderByField(sortBy, orderDirection);
You have the following methods which will be properly translated to SQL:
OrderByField, ThenByField, Paginate, SortAndPaginate