Post banner

Where() Select()

This post is quick intro for beginners. I’ll introduce you to 2 Linq methods Select and Where. We use those functions to manipulate data set.

All 2 can be applied to all types implementing IEnumerable interface. It means that you can apply them to data retrieved from database (IQueryable), list (List/IList implements IEnumerable), arrays (which also implements IEnumerable) and others.

It’s important to know that each one of those functions return new IEnumerable. Even if we execute these methods on array (e.g. int[]) it returns enumerable (e.g. IEnumerable<int>). Note that it works a bit different for IQueryable and database operations. Since this is an introductory level post I’ll show you how to use them using array based examples.

Select()

With Select we can map/project data to new form. It means that we can use it make something with every element.

var numbers = new [] { 1, 2, 3, 4, 5 };

// take each number and multiply it by itself
var newNumbers = numbers.Select(number => number * number);

// take each number and put it into a string
var numberMessages = numbers.Select(number => $"I say {number}");

// take each number and put it into new class
var people = numbers.Select(number => new Person { Id = number });

Where()

We use Where when we want to filter data. So it checks every element and returns only elements which matches critera.

var numbers = new [] { 1, 2, 3, 4, 5 };

// take each number make sure it's an odd number
var oddNumbers = numbers.Where(number => number % 2 == 1);

var names = new [] { "Adam", "Eve" };

// take each name and find only the ones that start with and "A"
var foundNames = names.Where(name => name.StartsWith("A"));

Chaining Select and Where

Since both of these functions return IEnumerable we can chain them. Take a look at this example:

var names = new [] { "Adam", "Amy", "Eve" };

// take each name and find only the ones that start with and "A"
// then create an sentence with given name
var foundNames = names.Where(name => name.StartsWith("A")).Select(name => $"My name is {name}");