开发者

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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜