If I have user input from a text box in c#, and have a CSV file of words for example with user input being: "Wow that's cool LOL" and the CSV file:
LOL Laughing Out Loud
ROFL Rolling On Floor Laughing
How would I compare the input text to find any matches in the file? How would I load the file?
You can do:
string input = "Wow that's cool LOL";
string[] splitArray = input.Split();
bool ifFound = File.ReadLines("yourCVSFilePath.csv")
.Any(line => splitArray.Any(line.Contains));
It is doing:
If you want to perform string comparison ignoring case then you can do:
bool ifFound = File.ReadLines("yourCVSFilePath.csv")
.Any(line =>
splitArray.Any(sa =>
line.IndexOf(sa, StringComparison.CurrentCultureIgnoreCase) > -1));
You can use File.ReadLines
to read the lines from the csv file and LINQ to filter them:
string input = "Wow that's cool LOL";
string[] words = input.Split();
char delimiter = '\t'; // for example
IEnumerable<string> matchingLines = File.ReadLines("yourCVSFilePath.csv")
.Where(line => words.Intersect(line.Split(delimiter)).Any())
.ToList(());
The Intersect
... Any
approach is an optimized version of this alternative query:
......
.Where(line => words.Any(word => line.Split(delimiter).Contains(word)))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.