Show Navigation Next Topic  »

Rule-Based Data Filtering Using LINQ to Object Provider

This topic illustrates the use of Code Effects' data filtering capabilities using the LINQ to Object provider. The goal is to allow the end user to create a business rule that will be used to filter out unwanted items from an in-memory collection of source objects.

To begin, let's create three classes: one base and two descendants. We will use these classes as our source objects:

class ClassA
	public int Id { getset; }
	public string FirstName { getset; }
	public string LastName { getset; }
class ClassB : ClassA
	public string Email { getset; }
class ClassC : ClassA
	public DateTime DOB { getset; }

Then let's create a web page, add a Rule Editor, set its Mode property to Filter, and give it ClassA as a source object. If we were to build the project and deploy it to a server, the end user(s) could create and save a filter like this one (remember that filters are just evaluation type business rules):

Get instances where ID is greater than 3 or (FirstName is John and LastName is Doe)

Assuming that we saved this filter somewhere in a database, we can use it in any .NET code against any IEnumerable<> collection of ClassA instances to filter out those that don't satisfy the conditions in the filter:

using System;
using System.Linq;
using System.Collections.Generic;
using CodeEffects.Rule.Core;

class Test
	public void Testing()
		string rule = YouRuleStorage.GetRuleXml();
		ClassA[] array = new[]
			new ClassA { Id = 1, FirstName = "John", LastName = "Smith" },
			new ClassB { Id = 2, FirstName = "Mike", LastName = "Doe" },
			new ClassC { Id = 3, FirstName = "John", LastName = "Doe" },
			new ClassB { Id = 6, Email = "test@test.test" },
			new ClassC { Id = 8, DOB = DateTime.Now }
		IEnumerable<ClassA> result = array.Filter(rule);
		foreach(var item in result)
		// Produces:
		// 3
		// 6
		// 8

As you can see, it takes very little effort to create very complex filters and use them against IEnumerable data of any size by employing the Filter extension method. LINQ To Object filtering in Code Effects is very efficient and extremely fast.

Post your questions on Stackoverflow and become a part of our growing community

Comments: 0