-2

I just want to take the first element from a list and add it to a file. My problem is that I am not sure why the function "take" does not work, is not compiling because of it.

ListBox does not contain a definition for 'First' and no extension method 'First' accepting a first argument of type 'ListBox' could be found (are you missing a using directive or an assembly reference?

var firstItem = Ingredients.Take(1);

File.AppendAllText("Pizza.txt", firstItem + Environment.NewLine);

2 Answers2

2

Take will create an IEnumerable with the number of elements that is specified as an argument. You are looking for First()

var firstItem = Ingredients.First();

File.AppendAllText("Pizza.txt", firstItem + Environment.NewLine);

If the list is empty First will throw an exception. FirstOrDefault will return null (or the type default if the IEnumerable is of a struct) if the list is empty, Depending on your use case, you should decide which is better for you.

Edit

The list in the question, is not List<T> but rather a ListBox as was clarified. You can take the Items property, use Cast to get an IEnumerable<T> and then use Fist. I am assuming the objects in the ListBox are string but you should change that to whatever type you are using:

listBox1.Items.Cast<string>().FirstOrDefault();  
Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357
0

Use .First() or .FirstOrDefault():

using System.Linq; // don't forget to add this.

var firstItem = yourList.First();
A-Sharabiani
  • 17,750
  • 17
  • 113
  • 128