5

I would like to return all elements but the last element. I looked at maybe using the Skip() method but got confused. Can anyone help me out please?

Thank you

user1290653
  • 775
  • 3
  • 11
  • 23

5 Answers5

12

You can't use Skip() in this case but you must use Take().

var result = list.Take(list.Length-1);
Omar
  • 16,329
  • 10
  • 48
  • 66
3

Use Take:

list.Take(list.Length-1);
ionden
  • 12,536
  • 1
  • 45
  • 37
1

You can use Enumerable.Take() for this:

var results = theArray.Take(theArray.Length - 1);

This will let you enumerate all elements except the last in the array.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
0

You can do the following:

var array = ...;
var arrayExceptLasElement = array.Take(array.Length-1);

Hope that helps!

aKzenT
  • 7,775
  • 2
  • 36
  • 65
0

Update with .NET Standard 2.1 (2018+)

You can now do this directly with LINQ's SkipLast like this:

var xs = new List<string>() {"A","B","C"};
var firstPart = xs.SkipLast(1);
Console.WriteLine(string.Join(",", firstPart)); // A,B

Demo in DotNetFiddle

KyleMit
  • 30,350
  • 66
  • 462
  • 664