Sandun Tharaka
Sandun Tharaka

Reputation: 747

Get first 10 lines and last 10 lines in textbox c#

I need to get the first 10 lines and last 10 lines on a multiline text in a textbox in a Windows Forms application.

ex.(textbox values)
Chicken
Chinese
Beef
Pork
Mutton
Fish
Prawn
Vegetarian
--
---

Upvotes: 1

Views: 1449

Answers (3)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

You can use Linq:

  var source = myTextBox.Lines;

  var first = source.Take(10);
  var last = source.Skip(source.Length - 10);

Now, let's print out the first values into, say, myReportTextBox:

 myReportTextBox.Text = String.Join(Environment.NewLine, first);

Upvotes: 2

Cee McSharpface
Cee McSharpface

Reputation: 8726

The System.Windows.Forms.TextBox inherits from TextBoxBase, which has a property:

public string[] Lines { get; set; }

You can query this property for its length, and when it has more than 10 elements (it is a plain array-of-string), then you can take the first ten and last ten from there. If it is a requirement that the first ten and last ten do not overlap, then you will need to ensure that the array count is at least 20.

Upvotes: 0

asdf_enel_hak
asdf_enel_hak

Reputation: 7640

var r1 = textBoxValues.Select(t=>t.values).Take(10);

var r2 = textBoxValues.Select(t=>t.values).Reverse().Take(10);

Upvotes: 7

Related Questions