Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check two List<int>'s for the same numbers

Tags:

I have two List's which I want to check for corresponding numbers.

for example

List<int> a = new List<int>(){1, 2, 3, 4, 5}; List<int> b = new List<int>() {0, 4, 8, 12}; 

Should give the result 4. Is there an easy way to do this without too much looping through the lists?

I'm on 3.0 for the project where I need this so no Linq.

like image 688
Gerrie Schenck Avatar asked Jan 26 '09 14:01

Gerrie Schenck


People also ask

How do you check if 2 items in a list are the same python?

Python sort() method and == operator to compare lists We can club the Python sort() method with the == operator to compare two lists. Python sort() method is used to sort the input lists with a purpose that if the two input lists are equal, then the elements would reside at the same index positions.

How can I check if two lists are the same in C#?

To determine if two lists are equal, where frequency and relative order of the respective elements doesn't matter, use the Enumerable. All method. It returns true if every element of the source sequence satisfy the specified predicate; false, otherwise.

How do you check if a list contains an object c#?

To check if an element is present in the list, use List. Contains() method.

How do you check if two lists have the same elements?

If the length of the lists are the same, we will sort the two lists. Then we will compare the lists using the == operator to check whether the lists are equal or not. If the sorted lists are equal, it will establish that both the original lists contain the same elements.

How to check if two lists are identical in Python?

Using Counter (), we usually are able to get frequency of each element in list, checking for it, for both the list, we can check if two lists are identical or not. But this method also ignores the ordering of the elements in the list and only takes into account the frequency of elements.

How to find if two numbers have the same number of digits?

Given two integers A and B, the task is to check whether both the numbers have an equal number of digits. Approach: While both the numbers are > 0, keep dividing both the numbers by 10. Finally, check if both the numbers are 0.

How do you find the sum of two lists in Python?

But this method also ignores the ordering of the elements in the list and only takes into account the frequency of elements. Using sum () + zip (), we can get sum of one of the list as summation of 1 if both the index in two lists have equal elements, and then compare that number with size of other list.


1 Answers

You can use the .net 3.5 .Intersect() extension method:-

List<int> a = new List<int>() { 1, 2, 3, 4, 5 }; List<int> b = new List<int>() { 0, 4, 8, 12 };  List<int> common = a.Intersect(b).ToList(); 
like image 58
ljs Avatar answered Sep 22 '22 15:09

ljs