Take the 2-minute tour ×

I have two list:

  List<int> data1 = new List<int> {1,2,3,4,5};
  List<string> data2 = new List<string>{"6","3"};

I want do to something like

var newData = data1.intersect(data2, lambda expression);

The lambda expression should return true if data1[index].ToString() == data2[index]

share|improve this question
possible duplicate of Check two List<int>'s for the same numbers –  Joshua Drake Feb 22 at 22:28
@JoshuaDrake I don't think it's a duplicate; that question does not consider using a lambda for custom determination of equality. –  Approaching Darkness Fish Feb 23 at 3:58
@ValekHalfHeart I probably should have just noted it as related, I somehow missed the difference in data types in this question. –  Joshua Drake Feb 24 at 18:36

2 Answers 2

up vote 22 down vote accepted

You need to first transform data1, in your case by calling ToString() on each element.

Use this if you want to return strings.


var newData = data1.Select(i => i.ToString()).Intersect(data2);

Use this if you want to return integers.


var newData = data1.Intersect(data2.Select(s => int.Parse(s));

Note that this will throw an exception if not all strings are numbers. So you could do the following first to check:

int temp;
if(data2.All(s => int.TryParse(s, out temp)))
    // All data2 strings are int's
share|improve this answer
Thank you, but I want it to return the integer, not the string –  Merni Aug 25 '11 at 9:31
See my edit for the alternative, returning integers. –  George Duckett Aug 25 '11 at 9:36

From performance point of view if two lists contain number of elements that differ significantly, you can try such approach (using conditional operator ?:):

1.First you need to declare a converter:

Converter<string, int> del = delegate(string s) { return Int32.Parse(s); };

2.Then you use a conditional operator:

var r = data1.Count > data2.Count ?
 data2.ConvertAll<int>(del).Intersect(data1) :
 data1.Select(v => v.ToString()).Intersect(data2).ToList<string>().ConvertAll<int>(del);

You convert elements of shorter list to match the type of longer list. Imagine an execution speed if your first set contains 1000 elements and second only 10 (or opposite as it doesn't matter) ;-)

As you want to have a result as List, in a last line you convert the result (only result) back to int.

share|improve this answer

Your Answer


