c# - Take the first five elements and the last five elements from an array by one query using LINQ -


i have been asked co-worker: possible take first 5 elements , last 5 elements 1 query array?

int[] somearray = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 }; 

what i've tried:

int[] somearray = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 }; var firstfiveresults = somearray.take(5); var lastfiveresults = somearray.skip(somearray.count() - 5).take(5); var result = firstfiveresults; result = result.concat(lastfiveresults); 

is possible take first 5 elements , last 5 elements 1 query?

you can use .where method lambda accepts element index second parameter:

int[] somearray = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 };  int[] newarray = somearray.where((e, i) => < 5 || > somearray.length - 6).toarray();  foreach (var item in newarray) console.writeline(item); 

output:

0, 1, 2, 3, 4, 14, 15, 16, 17, 18 

Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -