Tuesday, June 30, 2009

Remove List Elements That Exist in Another List

Problem:

We have two lists:


List bannedList = new List { "one", "three", "seven" };
List myList = new List { "one", "two", "three", "four", "five", "six" };


We need to keep only those entries in myList that are not contained in bannedList.

First of all, the conventional C# 1.0 approach to this problem:

List listDistinct = new List();
foreach (string elem in myList )
{
if (!bannedList.Contains(elem))
{
listDistinct.Add(elem);
}
}


Now, let's use lambda expressions to arrive at a much shorter syntax.

List listDistinct= myList .FindAll (elem => !bannedList.Contains(elem));
listDistinct.ForEach(elem=>Console.WriteLine(elem));
The result is:
two
four
five
six

By the way, if the first statement returns a List, you can chain template methods as follows:

myList.FindAll (elem => !bannedList.Contains(elem))
.ForEach(elem=>Console.WriteLine(elem));


But the easiest approach that does not involve creating a third list is to use the RemoveAll template method:

myList.RemoveAll(elem => bannedList.Contains(elem));

Thursday, June 11, 2009

Easy Syntax to Print List Elements

Create a list.
List <string> myList = new List <string> { "a", "b", "c", "d"};

a list-printing delegate :
Action <string> print = elem => { Console.WriteLine(elem);};

a statement:
myList.ForEach(print);