Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delimit strings in each line of a text file and compare them to a user input

Tags:

c#

csv

delimiter

My goal is to match the users input into a field with data in a text file.

1000|I-002096.02.02|EL|MISCMI
1000|I-002097.02.02|EL|ESYEED
1000|I-002098.02.02|EL|MISCCA
1000|I-002099.02.02|EL|MISCCA
1000|I-002100.02.02|EL|MISCCA
1000|I-002101.02.02|EL|USQUIC00
1000|I-002102.02.02|EL|MISCMI

The portion after the first "|" delimiter is what I need to check against the users input. (users input is stored in TxtWBS.Text in the code below)

This is what I have tried but this only works when each line has nothing to delimit.

string[] wbslist = File.ReadAllLines(filePath);
bool wbsExists = Array.Exists(wbslist, element => element == TxtWBS.Text);
    if (wbsExists)
       /*leave empty*/;
    else
       errMessage += "This WBS does not exist" + Environment.NewLine;

I expect to be able to check if the users input exists in the text file.

like image 500
Reza Avatar asked Dec 08 '22 11:12

Reza


2 Answers

This could be done with a single line in Linq. Change your test to:

bool wbsExists = wbslist.Any(x => x.Contains(TxtWBS.Text));

And if you are not sure about the case of the input you can have

bool wbsExists = wbslist.Any(x => -1 != x.IndexOf(TxtWBS.Text, StringComparison.CurrentCultureIgnoreCase));

More, if you want to check an exact match against the second item in the line then

bool wbsExists = wbslist.Select(x => x.Split('|')[1]).Any(k => k == TxtWBS.Text);

Consider also to change the loading of your text data to

var wbslist = File.ReadLines(filePath);

File.ReadLines doesn't read all the lines in memory immediately but returns an IEnumerable<String> that is more suited in Linq expressions

like image 71
Steve Avatar answered Feb 16 '23 01:02

Steve


You can use the following code. Read file and iterate line by line, splitting each line into array of strings by token '|'.

string[] wbslist = File.ReadAllLines(filePath);
foreach(string line in wbslist)
{
    string [] splittedLine = line.Split('|');
    // I assume you need the second element in the delimited line
    if(string.Equals(splittedLine[1], TxtWBS.Text, StringComparison.OrdinalIgnoreCase))
        Console.WriteLine("Website found");
}
like image 23
Iskander Raimbaev Avatar answered Feb 15 '23 23:02

Iskander Raimbaev