C # place an element in the array to the first position,
How to retrieve elements that meet certain conditions in the array and put them at the beginning of the array, that is, the index is 0?
The idea is roughly as follows:
→ Locate the array element that meets the conditions, assign it to a temporary variable temp, and write down the index position of the array element. Assume It is index.
→ In the source array, copy the array elements of the index to another target array starting from the array element whose index is 0.
→ Assign the Temporary Variable temp to the position where the index of the target array is 0.
public static class ArrHelper
{
/// <summary>
/// Extend the array of type T to move the elements that meet the conditions to the beginning of the array
/// </summary>
/// <typeparam name="T"></typeparam>
/// <Param name = "arr"> source array </param>
/// <Param name = "match"> lamda expression </param>
/// <returns></returns>
public static bool MoveToFront<T>(this T[] arr, Predicate<T> match)
{
// If the array length is 0
if (arr.Length == 0)
{
return false;
}
// Obtain the index of the array element that meets the conditions
var index = Array.FindIndex(arr, match);
// If no array element meets the conditions is found
if (index == -1)
{
return false;
}
// Assign an array element that meets the conditions to a temporary variable
var temp = arr[index];
Array.Copy(arr, 0, arr, 1, index);
arr[0] = temp;
return true;
}
public static void PrintArray<T>(T[] arr)
{
foreach (var item in arr)
{
Console.Write(item + " ");
}
Console.WriteLine();
}
}
The above is an extension for generic arrays, so you can directly use an array instance to call the extension method.
class Program
{
static void Main(string[] args)
{
int[] intArr = new int[]{1, 2, 3, 4, 5};
ArrHelper.PrintArray(intArr);
intArr.MoveToFront(i => i == 3);
ArrHelper.PrintArray(intArr);
Console.ReadKey();
}
}