Get an index of array and remove everything left of that index
I have an array of int
s
int[] RowOfints = 1,2,3,4,5,6,7,8,9;
if i enter for example value 4
i want to remove 1,2,3
from array and return what's left.
How to do th开发者_StackOverflowat?
If you don't want to use LINQ:
int[] newRowOfInts = new int[RowOfInts.Length - index];
Array.Copy(RowOfInts, index, newRowOfInts, 0, newRowOfInts.Length);
Using Skip extension in LINQ.
int[] newArray = RowOfInts.Skip(value).ToArray();
I'm interpreting your question that you want to find the index for the value 4
and then take everything starting from that index position.
var result = RowOfInts.SkipWhile(item => item != 4); // optionally, .ToArray()
result
will be an IEnumerable<int>
consisting of 4 .. 9
. If you want a concrete array, you can use the optional ToArray()
extension method as well. If no elements in the array match the given criteria, you will get a zero-length sequence.
OK, now that I understand the question better, I will post my version of the actual requirements (again perversely emphasising effeciency over readability):
private static int[] RemoveBeforeValue(int[] source, int value)
{
if (source == null)
return null;
int valueIndex = 0;
while (valueIndex < source.Length && source[valueIndex] != value)
valueIndex++;
if (valueIndex == 0)
return source;
int[] result = new int[source.Length - valueIndex];
Array.Copy(source, valueIndex, result, 0, result.Length);
return result;
}
OLD ANSWER
If you want to do it the hard (but efficient!) way, then you can do this (assuming you want to remove values less than the supplied value):
private static int[] RemoveValuesLessThan(int[] source, int newMinimum)
{
if (source == null)
return null;
int lessThanCount = 0;
for (int index = 0; index < source.Length; index++)
if (source[index] < newMinimum)
lessThanCount++;
if (lessThanCount == 0)
return source;
int[] result = new int[source.Length - lessThanCount];
int targetIndex = 0;
for (int index = 0; index < source.Length; index++)
if (source[index] >= newMinimum)
result[targetIndex++] = source[index];
return result;
}
For a sequential array of ints
public static void RemoveIntsBefore(int i)
{
int[] RowOfints = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
for (int k = 0; k < RowOfints.Length; k++)
{
if (RowOfints.ElementAt(k) < i)
{
RowOfints[k] = i;
}
}
RowOfints = RowOfints.Distinct().ToArray();
//this part is to write it on console
//foreach (var item in RowOfints)
//{
// Console.WriteLine(item);
//}
//Console.ReadLine();
}
with this one your array does not have to be sequential
public static void RemoveIntsBefore(int i)
{
int[] RowOfints = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 1,2 };
Console.WriteLine("OUTPUT");
foreach (var item in Enumerable.Range(i-1, RowOfints.Length + 1 - i).ToArray())
{
Console.WriteLine(RowOfints[item]);
}
Console.ReadLine();
}
using System.Linq; ....
int[] RowOfints = {1,2,3,4,5,6,7,8,9};
int[] Answer = RowOfints.Where(x => x != 1 && x != 2 && x != 3).ToArray()
精彩评论