Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Saturday, May 26, 2018 7:08 PM
Hi there,
I have an array of integers, like:
a[0]=1; a[1]=5; a[2]=89; a[3]=125; a[4]=203
and variable divNo containing the number I have to find in that array.
If we assume that divNo is 89, array has to be split in two: first one from a[0] to a[2]=divNo=89 and second one from a[3] to a[4].
How do I do that?
Thanks a lot in advance.
Kind regards
All replies (5)
Saturday, May 26, 2018 8:22 PM ✅Answered
Following will done the trick for you
class Program
{
static void Main(string[] args)
{
int[] a = new[] { 1, 5, 89, 125, 203 };
var divNo = 89;
var index = Array.IndexOf(a, divNo);
if (index > -1)
{
Split(a, index + 1, out int[] b, out int[] c);
Console.WriteLine("Elements in First Array");
foreach (var i in b)
{
Console.WriteLine(i);
}
Console.WriteLine("Elements in Second Array");
foreach (var i in c)
{
Console.WriteLine(i);
}
Console.ReadLine();
}
}
public static void Split<T>(T[] array, int index, out T[] first, out T[] second)
{
first = array.Take(index).ToArray();
second = array.Skip(index).ToArray();
}
}
Saturday, June 9, 2018 5:43 PM ✅Answered
Use LINQ
int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var first = numbers.Take(Array.IndexOf(numbers, 6) + 1);
var rest = numbers.Skip(Array.IndexOf(numbers, 6) + 1);
Sunday, June 10, 2018 10:31 PM ✅Answered
var first = numbers.TakeWhile(n => n <=89);
var second = numbers.SkipWhile(n => n<= 89);
Saturday, May 26, 2018 9:39 PM
Thanks a lot Nasser Malik, it works great!
Regards
Monday, June 11, 2018 1:10 PM
even better!