Intersect Two Lists in C#

后端 未结 4 837
情书的邮戳
情书的邮戳 2020-11-27 19:40

I have two lists:

  List data1 = new List {1,2,3,4,5};
  List data2 = new List{\"6\",\"3\"};
4条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-27 20:23

    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 del = delegate(string s) { return Int32.Parse(s); };
    

    2.Then you use a conditional operator:

    var r = data1.Count > data2.Count ?
     data2.ConvertAll(del).Intersect(data1) :
     data1.Select(v => v.ToString()).Intersect(data2).ToList().ConvertAll(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.

提交回复
热议问题