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?
3 Answers 3
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.
2 Comments
"appname.exe.config".Split('.') == new [] { "appname", "exe", "config" }; the last element of that is "config", as expected..Last...was going by the .SkipfileNames.Select(s => Path.GetExtension(s)).Select(e => string.IsNullOrEmpty(e) ? "unknown" : e);
1 Comment
Path.GetExtension includes the leading "." on the extension -- you'll want to strip that off to get the desired result.When you use String.Split, you get an array of strings. The string given is broken up at each occurence of the specified character. If the character doesn't occur, you get an array of length 1. In this case, the Last element is actually the first.
While it may be possible to do this with LINQ (handling files like abc.def.exe might be tricky), there is a simpler way. Use the Path.GetExtenstion method.
_filesNameobject look like? You may be able to use Path.GetExtension