简体   繁体   中英

C# Match CSV String

I am trying to figure out how to write a C# function that returns true if there is a "match" between two strings. The numbers in the string will always be sorted in asc order.

string1: 1,3
string2: 1,2,3

The function should return true if all the numbers in string1 are found in string2. In the example above the return value should be true.

string1: 1,2,4
string2: 1,2,3

In the example above the return false should be false because not all numbers in string1 are found in string2.

The base case of string1 being an empty string should always return true no matter what string2 contains.

I am thinking of splitting both strings into arrays and trying to do a match and would also be interested in a regex option. Open to any ideas you may have.

I can handle writing the function so really just looking for ideas on the "best" way to accomplish this. And by "best" I mean the option that you think performances the fastest (and yes, I will test on my hardware for performance before moving into production).

The strings at most would have 10 numbers in them, if that helps. We will never see a string with hundreds of numbers.

If the format is strict and you cannot have something like 1, "1,2,3", 2 you can use String.Split and LINQ:

bool allInOneInTwo = !string1.Split(',').Except(string2.Split(',')).Any();

Enumerable.Except returns the set difference of two sequences and is very efficient. Because it's executed lazily Enumerable.Any will return on the first match.

Since you've mentioned that it must be efficient because it's executed up to 100k times per day and that you expect that it takes less than a couple of seconds at most: with your sample above it takes only 140 milliseconds to execute it 100k times on my PC. But both arrays are very small. Except would make a greater difference if they were larger.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM