How to Perform Multiple Actions on Items in a List Using LINQ Select
Sometimes we'll have a list of data which needs to have multiple actions performed on each item in the list. An example might be to write the item's value to a log, call a function using the item as a param to the function, and then convert the item to a new type. In the tradional approach, we would build a foreach loop, and perform these actions in the loop.
I am going to show you how to use LINQ to perform multiple actions on each item in an IENumerable list using LINQ. Depending on your desired outcome, you could use different LINQ extensions. In my example below, we will be using LINQ Select.
Another use of this technique is for using LINQ to SQL or during deferred execution. You could output each item's value to the console or a log as a demonstration of when deferrede excecution actually processes the item.
In the example below, we will take a list of integers in string format, output their original value, call a function which outputs the item's length, and finally convert the item to an int to populate a new List<int>.
Example of Performing Multiple Actions on Each Item in a List using LINQ Select
static void OutputItemLength(string item)
{
Console.WriteLine(string.Format("\tItem Length: {0}", item.Length));
}static void Main(string[] args)
{
// holds the final list
List<string> SampleList = new List<string>() { "10", "21", "32", "43", "564", "68", "79", "811", "92468", "10" };// convert the list using Cast
List<int> SampleIntList = SampleList.Select<string, int>(x =>
{
// log the item
Console.WriteLine(x);// run a func on the item
OutputItemLength(x);// convert the item for the final result
return Convert.ToInt32(x);
}
).ToList();/*
* Output:
* 10
* Item Length: 2
* 22
* Item Length: 2
* 32
* Item Length: 2
* 43
* Item Length: 2
* 564
* Item Length: 3
* 68
* Item Length: 2
* 79
* Item Length: 2
* 811
* Item Length: 3
* 92468
* Item Length: 5
* 10
* Item Length: 2
*/Console.ReadLine();
}
There are a few things you need to keep in mind, using this technique:
- You must use the curly brackets { } to wrap the code inside your Lambda function. This allows you to reuse the variable (x in our example) multiple times.
- Because LINQ Select() expects a return result from the Lambda expression, your last statement must be a return statement.
- This return is only used to exit the Lambda function and return a value to the LINQ Select() statement
As you can see, this can be a very powerful tool for list handling.
If you have questions, comments, or suggestions, please feel to post them in the LINQ Exchange Forum


