Question

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?

Was it helpful?

Solution

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();

OTHER TIPS

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

enter image description here

Regex reg = new Regex( "-" );
string filename = "NewReport-20140423_17255375-BSIQ-2wd28830-841c-4d30-95fd-a57a7aege412.zip";
var parts = reg.Split( filename, 4 );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top