How do find line in a List
I have a text file that I am reading each line of using sr.readline()
List.Contains(string)
will tell you if a list already contains an element.
So you will wanna do something like:
if (previousList.Contains(line)){
newList.Add(line);
}
You could loop through this logic:
public void DoWhatYouAreAskingFor(StreamReader sr, List<string> list)
{
string line = sr.ReadLine();
if (!list.Contains(line))
{
list.Add(line);
}
}
You could do something like this.
List<string> listOfStrings = new List<string>() { "foo", "baz", "blah"};
string fileName = @"C:\Temp\demo.txt";
var newlist = (from line in File.ReadAllLines(fileName)
join listItem in listOfStrings
on line equals listItem
select line).ToList();
Edit: as a note, my solution shortcircuits the use of the streamreader and trying to find elements in another list and rather uses LINQ to join the elements of an existing list of strings with the lines from a given input file.
List.Contains(input) is certainly fine, and if you have a lot of inputs to filter, you may want to consider converting the searchable list to a HashSet.
精彩评论