Sep 10, 2013

Interactive Extensions


LINQ provides lot of ways to query the objects or XML. But we might need some more features\extensions which will be handy in real development. Let us explore a library which provides more extensions\features to the existing framework.


Introduction

The Reactive Extensions (Rx) is a library for composing asynchronous and event-based programs using observable sequences (provides notification information) and LINQ-style query operators.

The Interactive Extensions (Ix) is a .NET library which extends LINQ to Objects to provide many of the operators available in Rx but targeted for IEnumerable. In simple terms, it provides a lot of new features to LINQ to Object which is not available in Framework. Ix is sub-set of Rx.

This will install System.Interactive.dll file. EnumerableEx class provides a set of additional static methods that allow querying enumerable sequences.


Execute below command in Nuget Package Manager Console to install:
install-package Ix-Main


Let us discuss few features:

Do: This lazily invokes an action for each value in the sequence. That means it invokes\executes an action for each value in enumeration.


Sample Code:
static void Main(string[] args)
{
      DisplayNumbersDo();
}
static void DisplayNumbersDo()
{

      int addnumber = 10;
      //Let us create a set of numbers 
      var numbers = new int[] { 6, 1, 4, 2, 6 };

      var result = numbers.Do(n => Console.WriteLine(n + addnumber));
      Console.WriteLine("Before Enumeration");
      foreach (var item in result)
      {
          //The action will be invoked when we actually enumerate 
      }
      Console.WriteLine("After Enumeration");
      Console.ReadLine();
}


ForEach: Enumerates the sequence and invokes the given action for each value in the sequence.

Sample Code:
static void Main(string[] args) { List names = new List { "ram", "nagesh" }; names.ForEach(s => Console.WriteLine(s)); ; Console.ReadLine(); }


Scan: Generates a sequence of accumulated values by scanning the source sequence and applying an accumulator function. 

Sample Code:
static void Main(string[] args) { List names = new List { "ram ", "nagesh" }; names.Scan((x,y) => x + y).ForEach(s => Console.WriteLine(s)); Console.ReadLine(); }



Below are few more methods which might be useful:

Repeat: Repeats and concatenates the source sequence infinitely.

SkipLast: Bypasses a specified number of contiguous elements from the end of the sequence and returns the remaining elements.

TakeLast: Returns a specified number of contiguous elements from the end of the sequence.


You can install Interactive Extensions in Visual Studio 2010 also.





No comments:

Post a Comment