No Count overload for a String Split method in Sil

2019-08-31 17:29发布

问题:

Reference to question at Splitting a filename

In the Silverlight Application since there is no Count overload, I require the expected result as four string elements.

NewReport
20140423_17255375
BSIQ
2wd28830-841c-4d30-95fd-a57a7aege412.zip

This line of code is getting build errors in my silverlight application

var strFileTokens = filename.Split(new[] { '-' }, 4, StringSplitOptions.None);

Build Error: Error 4

The best overloaded method match for 'string.Split(string[], int, System.StringSplitOptions)' has some invalid arguments    C:\TestSolution\Reporting.cs    287

How to get the above four string elements?

回答1:

As you've mentioned, the overload that takes a maximum count of returned sub-strings is not supportewd in silverlight. Here is the silverlight overview.

So you need to use a workaround, if you want to take only 4. You can use Split + Enumerable.Take:

string[] strFileTokens = filename
    .Split(new[] { '-' }, StringSplitOptions.RemoveEmptyEntries )
    .Take(4)
    .ToArray();

I would use StringSplitOptions.RemoveEmptyEntries to omit empty tokens. If you don't need it as array you can omit ToArray and execute it lazily which can be more efficient.

Update: now i've recognized from your other question that you want to take the first three elements and the last. So if this is your file-name:

string filename = "NewReport-20140423_17255375-BSIQ-2wd28830-841c-4d30-95fd-a57a7aege412.zip";

You want this string[]:

"NewReport" 
"20140423_17255375"
"BSIQ"
"2wd28830-841c-4d30-95fd-a57a7aege412.zip"  

You could use LINQ's Skip and Take + string.Join to get one string for the last tokens:

string[] allTokens = filename.Split(new[] { '-' }, StringSplitOptions.RemoveEmptyEntries);
var firstThreeToken = allTokens.Take(3);
var lastTokens = allTokens.Skip(3);
string lastToken = string.Join("-", lastTokens);
string[] allToken = firstThreeToken.Concat(new[] { lastToken }).ToArray();


回答2:

You can use the Regex.Split method which offers an overload that takes the count param.

Regex reg = new Regex( "-" );
string filename = "NewReport-20140423_17255375-BSIQ-2wd28830-841c-4d30-95fd-a57a7aege412.zip";
var parts = reg.Split( filename, 4 );