views:

86

answers:

3

I have a text file that I am reading each line of using sr.readline()
As I read that line, I want to search for it in a List that the line should have been added to previously, then add the line to a NEW (different) list. How do I do this?

+4  A: 

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);
}
jjnguy
A: 

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);
    }
}
Jaxidian
-1 That is not what he/she wants to do according to the description.
jjnguy
Actually the wording of the description doesn't say if they are looking for a postive or negative match, just that it should have been added, perhaps they are looking for strings which should of been added but were not. So you are both right / wrong
benPearce
@benP it is specifically stated that the line from the file should be added to a new (different) list if it is already in the old list.
jjnguy
A: 

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.

Anthony Pegram