If I have an array (1,2,3,4,5,6,7,8)
and another array (2,4,6)
How do I get a third array (1,3,5,7,8)
?
I can't use LINQ, I'm working on .NET CF 2.0. How can I do this without using LINQ or is there a LINQ resource compatible with .NET CF 2.0?
If I have an array (1,2,3,4,5,6,7,8)
and another array (2,4,6)
How do I get a third array (1,3,5,7,8)
?
I can't use LINQ, I'm working on .NET CF 2.0. How can I do this without using LINQ or is there a LINQ resource compatible with .NET CF 2.0?
For each element of the first array you check whether the second array contains it. If it doesn't then you add it to the result:
var array1 = new[] { 1,2,3,4,5,6,7,8 };
var array2 = new[] { 2,4,6 };
var result = new List<int>();
foreach (var value1 in array1)
{
bool exists = false;
foreach (var value2 in array2)
{
if (value1 == value2)
{
exists = true;
break;
}
}
if (!exists)
{
result.Add(value1);
}
}
// result is { 1,3,5,7,8 }
var intList = new List<int>();
for (var i = 0; i < mainArray.Length; i++) // loop through the first array
{
var exists = false;
for (var y = 0; y < otherArray.Length; y++) // loop through the next array
{
if (mainArray[i] != otherArray[y]) // if the values arent equal
{
exists = true;
break;
}
}
if (!exists)
{
intList.Add(mainArray[i]); // put them in the new list
}
}
Here is the foreach method:
foreach (var main in mainArray)
{
foreach (var other in otherArray)
{
// same logic as above
}
}
LINQ is only a simplified way of looping through elements in an enumerable.
Follow this pseudo code:
declare result
foreach item in array1
if array2 does not contain item
add item to result
hope this will be the shortest answer :)
int[] arr1 = new int[] { 1, 2, 3, 4, 5, 6, 7, 8 };
int[] arr2 = new int[] { 2, 4, 6 };
// copy the content of arr1 into a temporary List
List<int> temp = new List<int>(arr1);
// kick-out unneeded elements from temporary List
foreach (int toRemove in arr2) temp.Remove(toRemove);
// it's done
int[] result = temp.ToArray();