Shonna
Shonna

Reputation: 289

How do find line in a List

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?

Upvotes: 2

Views: 579

Answers (3)

Anthony Pegram
Anthony Pegram

Reputation: 126884

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.

Upvotes: 0

jjnguy
jjnguy

Reputation: 138884

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);
}

Upvotes: 4

Jaxidian
Jaxidian

Reputation: 13511

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);
    }
}

Upvotes: 0

Related Questions