Click here to Skip to main content
15,895,084 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all,

Can anybody tell me how to look for value in an array with similar elements or different & its index in the array & compare it with a array containing indices's of other data. Like for Ex:

In array1[6] = {1,0,0,1,0,2,0} here i need to check whether the array contains 1s in it & extract the index of 1s in the array. In this example we can see that the array contains 1s & their indices's are 0 & 4. I have got another array which contains the indices's of other data i.e., array2[2] = {2,5}. So here i need to compare indices's of array1 with the data of array2 if both are same some event will be triggered if not some other event.

Thanks in advance.
Posted

IT's not difficult to do, but the "normal" methods to speed it up don't work - you can't use Linq because it works on unordered sets, so it has no concept of "index". But the "brute force and ignorance" approach is pretty simple anyway:
C#
int[] myArray = { 1, 0, 0, 1, 0, 2, 0 };
int[] match = { 2, 5 };
List<int> indexes = new List<int>();
for (int i = 0; i < myArray.Length; i++)
    {
    if (myArray[i] == 1) indexes.Add(i);
    }
if (Enumerable.SequenceEqual(indexes, match))
    {
    Console.WriteLine("They match");
    }
 
Share this answer
 
Comments
Jagadisha_Ingenious 26-Apr-13 5:28am    
Hi @OriginalGriff: i get this type of error in the line8 of the code you have posted i am using visual studio 2010 with .net framework 4.0v. So can you tell me how to overcome this error.
"The type arguments for method 'System.Linq.Enumerable.SequenceEqual<tsource>(System.Collections.Generic.IEnumerable<tsource>, System.Collections.Generic.IEnumerable<tsource>)' cannot be inferred from the usage. Try specifying the type arguments explicitly."
OriginalGriff 26-Apr-13 5:46am    
Look at how you defined the two arrays (indexes and match in my case) - I'm betting you didn;t specify the type of one of them!
Arrays are sooo last century...

But seriously, you might want to put the indices in HashSet[^]s and then perform set operations on them.
 
Share this answer
 
Comments
Jagadisha_Ingenious 26-Apr-13 4:53am    
Hi PIEBALDconsult, actually what i require is i am saving the data in an array & the array is updated everytime & this updated data if it contains the same value in the same position i should not perform any task. If not equal perform some task.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900