I have below which is working for the 1st element...I just can't figure out how to do it for all elements on the arrays... thanks in advance
int[] ListNumb1 = new int[] { 2, 4, 6 };
int[] ListNumb2 = new int[] { 3, 1, 9 };
if (ListNumb1[0] < ListNumb2[0])
{
Console.WriteLine(ListNumb1[0]);
}
else
Console.WriteLine(ListNumb2[0]);
Console.ReadLine();
You can use the Enumerable.Zip
method to zip the 2 collections (arrays) together, and Math.Min
to get the lowest value.
var result = ListNumb1.Zip(ListNumb2, Math.Min)
Full Example
int[] ListNumb1 = new int[] { 2, 4, 6 };
int[] ListNumb2 = new int[] { 3, 1, 9 };
// Result will be an IEnumerbale<int>
var result = ListNumb1.Zip(ListNumb2, Math.Min)
Console.WriteLine(string.Join(",", result));
Output
2,1,6
Note : To get the output in an array, just Call ListNumb1.Zip(ListNumb2, Math.Min).ToArray()
Or you could use a classic for loop
// Allocate the array
var results = new int[ListNumb1.Length];
// Iterate over each element in both arrays
for (var i = 0; i < ListNumb1.Length; i++)
results[i] = Math.Min(ListNumb1[i], ListNumb2[i]);
Note 2 : Both these examples assume the arrays are of equal length, if that is not that case, you will need to validate and act accordingly
Additional resources
Applies a specified function to the corresponding elements of two sequences, producing a sequence of the results.
Returns the smaller of two numbers.
Concatenates the elements of a specified array or the members of a collection, using the specified separator between each element or member.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.