C# Linq: Zip method

string[] brands = new string[] { "BMW", "Mercedes", "Audi" };
string[] websites = new string[] { "www.bmw.com", "www.mercedes.com", "www.audi.com" };

var output = brands.Zip(websites, (b, w) => string.Format("{0} can be found at {1}", b, w));

foreach (var line in output)
  Console.WriteLine(line);

This gives you:

BMW can be found at www.bmw.com 
Mercedes can be found at www.mercedes.com 
Audi can be found at www.audi.com

More information at: http://msdn.microsoft.com/en-us/library/dd267698.aspx

Advertisements

Rx (Reactive Extensions)

Reactive Extensions (Rx) was added to Codeplex.com:

The project is actively developed by the Microsoft Open Technologies, inc., in collaboration with a community of open source developers.

The Reactive Extensions (Rx) is a library for composing asynchronous and event-based programs using observable sequences and LINQ-style query operators. Using Rx, developersrepresent asynchronous data streams with Observables , query asynchronous data streams usingLINQ operators, and parameterize the concurrency in the asynchronous data streams usingSchedulers. Simply put, Rx = Observables + LINQ + Schedulers.

Find out more on: https://rx.codeplex.com/

Select the index of a specific object via LINQ

This will search for the index of an object in a collection depending on a specific criteria.
When the object is not found in the collection, it will return an index with value -1.


string searchValue = "d";
List<string> items = new List<string>() { "a", "b", "c", "d", "e" };

int foundIndex = items.Select((x, i) => new { x, i })
.Where(x => x.x == searchValue)
.Select(x => x.i)
.DefaultIfEmpty(-1)
.First();

// specific code for LINQPad
foundIndex.Dump();

The result will be 3, because “d” has index 3 in the collection.

SelectMany in LINQ (C#)

This is an example of using SelectMany in Linq (Method notation):


string[] allItems = { "item1", "item2", "item3" };
string[] databaseItems = { "item2" };

var data = allItems
.SelectMany(item => databaseItems , (item, dbItem) => new { item, dbItem })
.Where(x => !x.item.Equals(x.dbItem, StringComparison.InvariantCultureIgnoreCase))
.Select(x => x.item);

foreach (var v in data)
Console.WriteLine(v.ToString());

// LinqPad specific code:
data.Dump();

The result is item1 and item3.
This example takes all the items from allItems that don’t exist in databaseItems.