How do I remove an element in an array that matches a certain condition, and then put it at the front of the array, where the index is 0?
The idea is roughly as follows:
→ Locate an array element that matches the criteria, assign it to a temp variable, and note the index position of the array element, assuming that index
→ In the source array, starting from an array element with index 0, copy the index array element to another destination
→ Assign temporary variable temp to the target array where the index is 0
Public Static class Arrhelper
{
<summary>
Expands an array of type T, moving the element that satisfies the condition to the front 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 length of the array is 0
if (arr.) Length = = 0)
{
return false;
}
Gets the index of the array element that satisfies the condition
var index = Array.findIndex (arr, match);
If an array element that satisfies the condition is not found
if (Index = =-1)
{
return false;
}
Assigning an array element that satisfies a condition 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 in arr)
{
Console.Write (item + "");
}
Console.WriteLine ();
}
}
The above is an extension to a generic array, so you can call an extension method directly using an array instance.
class Program
{
Static void Main (string[] args)
{
int New int []{1, 2, 3, 4, 5};
Arrhelper.printarray (intarr);
Intarr.movetofront (i = = 3);
Arrhelper.printarray (intarr);
Console.readkey ();
}
C # takes an element out of the array and puts it in the first position