Have you ever looked at sites that have real-time filtering of a grid or list of products and wondered "how can I do that?" Maybe you're developing a few intranet apps that would do well having this type of functionality. Perhaps you’ve looked around for good tutorials with examples so you can understand the process but you’re not even sure where to start?
The key to implementing this kind of filtering is to apply it to the underlying data source rather than the presentation grid. I'm going to focus on one approach to filtering that relies on LINQ and some extension methods.
Let's assume for this example that you know where your data is coming from and how to get it. Maybe you're calling a stored procedure to get your data and populating your grid from that. Perhaps you're using an ORM. Either way, you have the data, which consists of credit reports that can be optionally filtered by type (Competitor/Customer/Vendor), year or company. You’ve made a call to your business service to retrieve your data into an enumerable of credit reports and now need to filter them.
IEnumerable<CreditReport> allReports = businessService.GetAllCreditReports();
The first filter we need is a filter by type. Add a BusinessServiceExtensions
class to your project that looks like this:
public static class BusinessServiceExtensions
{
public static IEnumerable<CreditReport> FilteredByType(this IEnumerable<CreditReport> source,
ReportTypeOption reportType)
{
if (reportType == ReportTypeOption.None)
{
return source; }
return source.Where(x => x.ReportType == reportType);
}
}
We now need filtering for year and company. Add these 2 methods to your extensions class above:
public static IEnumerable<CreditReport>
FilteredByYear(this IEnumerable<CreditReport> source, int year)
{
if (year == 0)
{
return source;
}
return source.Where(x => x.Year == year);
}
public static IEnumerable<CreditReport>
FilteredByCompany(this IEnumerable<CreditReport> source, string company)
{
if (string.IsNullOrEmpty(company))
{
return source;
}
return source.Where(x => x.Company == company);
}
We can now easily combine these extension methods using a fluent interface, because each one returns an IEnumerable<CreditReport>
:
return allReports
.FilteredByType(reportType)
.FilteredByYear(year)
.FilteredByCompany(company);
View original article.