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?
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.
fileNames.Select(s => Path.GetExtension(s)).Select(e => string.IsNullOrEmpty(e) ? "unknown" : e);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With