Tuesday, October 9, 2007

LINQ to Textbox

var lines = textbox1.Lines.Select( l => l.Contains( "the" ) );

The point of this post is that LINQ is everywhere. Use it on whatever you want. The above shows the "Select" that LINQ adds to collections, arrays, etc when you include the System.Linq namespace. Below is the more SQL-like query syntax, with an added condition and a trim. It returns all the lines that have "the" in it.

var lines = from line in textbox1.Lines
where line.Contains( "the" ) && line.Length > 10
select line.Trim();

I wrote a simple application that has two large text boxes and a small text box. The example program only has 1 statement, which is the following.

txtResult.Lines = (from line in txtToSearch.Lines
where line.Contains(txtSearchString.Text)
select line).ToArray();

I get bug reports in large text files (which include historical bug data, call stack, loaded modules, etc) automatically emailed to me from our application. I can paste the bug report into the txtToSearch control, type in "up time" into the single line txtSearchString control, and the results are put into the multi-line txtResult control and it will pull out all the lines that have either system or program up times. LINQ is great.

No comments: