Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intersect Two Lists in C#

I have two lists:

  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]

like image 964
Merni Avatar asked Aug 25 '11 09:08

Merni


People also ask

How do you find the intersection of two linked lists in C?

Get count of the nodes in the first list, let count be c1. Get count of the nodes in the second list, let count be c2. Get the difference of counts d = abs(c1 – c2) Now traverse the bigger list from the first node till d nodes so that from here onwards both the lists have equal no of nodes.

How do you find the intersection of two lists?

To perform the intersection of two lists in python, we just have to create an output list that should contain elements that are present in both the input lists. For instance, if we have list1=[1,2,3,4,5,6] and list2=[2,4,6,8,10,12] , the intersection of list1 and list2 will be [2,4,6] .

How do you intersect in C#?

Firstly, set two lists. List<int> val1 = new List<int> { 25, 30, 40, 60, 80, 95, 110 }; List<int> val2 = new List<int> { 27, 35, 40, 75, 95, 100, 110 }; Now, use the Intersect() method to get the intersection between two lists.

How do you find the intersection of two lists in R?

In R, we can do this by using intersection function along with Reduce function.


2 Answers

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

Use this if you want to return strings.

List<int> data1 = new List<int> {1,2,3,4,5}; List<string> data2 = new List<string>{"6","3"};  var newData = data1.Select(i => i.ToString()).Intersect(data2); 

Use this if you want to return integers.

List<int> data1 = new List<int> {1,2,3,4,5}; List<string> data2 = new List<string>{"6","3"};  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 } 
like image 84
George Duckett Avatar answered Oct 12 '22 13:10

George Duckett


If you have objects, not structs (or strings), then you'll have to intersect their keys first, and then select objects by those keys:

var ids = list1.Select(x => x.Id).Intersect(list2.Select(x => x.Id)); var result = list1.Where(x => ids.Contains(x.Id)); 
like image 43
alexkovelsky Avatar answered Oct 12 '22 15:10

alexkovelsky