In this case, the source of the text is from a winforms textbox. I’m asking this primarily to learn more about LINQ and maybe to demonstrate its strength (easier to read than loops, in my opinion). This program had several requirements; the function had to get the text from the textbox, split it into its separate lines, remove empty and/or duplicate lines, and trim the lines.
Are these the only ways to do this? Are there other methods for this in C# (apart from looping through the list of lines and adding items that meet the criteria to a new list, array, etc.)?
1:
List<String> listOne = textBoxWords.Text
.Split(new char [] { '\r', '\n' })
.Select(s1 => s1.Trim())
.Where(s2 => !String.IsNullOrEmpty(s2))
.Distinct()
.ToList();
2:
List<String> listTwo = textBoxWords.Text
.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)
.Select(s1 => s1.Trim())
.Distinct()
.ToList();
UPDATE: This code was suggested, but only works if the strings don’t need to be trimmed.
3:
List<String> listThree = textBoxWords.Text
.Split(new char[] { '\r', '\n' },
.Where(s1 => !String.IsNullOrWhiteSpace(s1))
.Distinct()
.ToList();
I know it’s a) fairly specific, and b) could probably be implemented easier using a DataGrid, but the code I’m maintaining uses textboxes and I didn’t immediately want to rewrite them.
It’s not exactly the same as what you have since the result is a HashSet, but based on your scenario it looks like that may be the better data structure for what you are trying to accomplish.