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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s