I just wanted to go through a few examples of how to retrieve all the items in a list, that also exist in another list. This is one of those useful techniques which you may not need very often and so this post will act as a reminder.
To start with we need arrays.
var lista = new List<string>(){"one","two","three","four","five","six","seven"}; var listb = new List<string>(){"One","fortyfour","six"};
These examples are designed on the principle that we want to retrieve all the values from lista which also exist in listb. This can be done by using an explicit linq join,
result = from a in lista join b in listb on a.ToLower() equals b.ToLower() select a;
Although it could be written on a single line, this type of query is usually written over multiple lines for clarity. The same result could be achieved as below
result = lista.Where(a => listb.Any(b => a.ToLower() == b.ToLower()));
One method is not necessarily better than the other and I am sure there are a number of other ways the same result could be achieved.
I find using the string.Compare() method saves from having to keep converting to lower case.
var result = lista.Where(a => listb.Any(b => string.Compare(a,b,true) == 0));
If you were to output the contents of the result variable from both the above examples you would see they all produce the same result (based on the original array contents)
one six
The last example will retrieve all the items from lista where the text of the item is contained in the text of an item in listb.
var result = lista.Where(a => listb.Any(b => b.Contains(a)));
Note that the Contains method is case sensitive so the result would be
four six
because listb has an item that contains the text ‘four’, which is the text of an item in lista. Also both lists have an item with the same text ‘six’.