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.
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.
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.
To check if an element is present in the list, use List. Contains() method.
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.
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.
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With