Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string and set default value if separator not found WITH LINQ

Tags:

c#

linq

I have a similar question than this post: C# string splitting but it's bit old and use Regex as solution.

So here's my input (array of string)

foo.xml
bar.png
pdf

What I want is to retrieve the files extensions without dot and set "unknown" when no dot is found.

xml
png
unknown

What I tried that didn't work

_filesName.Select(a => a.Split('.').Select(b => string.IsNullOrEmpty(b) ? "unknown":b).Last());

return

xml
png
pdf // WRONG!! Why its not set to unknown?

Is it possible to do what I want using LINQ?

like image 897
John Avatar asked Dec 15 '22 10:12

John


2 Answers

Think about what your query does on "pdf":

a // "pdf"
.Split('.') // new [] { "pdf" } 
.Select(b => string.IsNullOrEmpty(b) ? "unknown":b) // new [] { "pdf" } 
.Last() // "pdf"

Any string will have non-null elements after Split, whether it contains the separator or not.

Probably you want something like this:

a // "pdf"
.Split('.') // new [] { "pdf" }
.Skip(1) // new [] {}
.DefaultIfEmpty("unknown") // new [] { "unknown" }
.Last() // "unknown"

That should work on all your cases.

like image 176
kevingessner Avatar answered Jan 28 '23 14:01

kevingessner


fileNames.Select(s => Path.GetExtension(s)).Select(e => string.IsNullOrEmpty(e) ? "unknown" : e);
like image 29
Boris B. Avatar answered Jan 28 '23 14:01

Boris B.