5

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?

asked May 20, 2013 at 16:00
2
  • What does the _filesName object look like? You may be able to use Path.GetExtension Commented May 20, 2013 at 16:02
  • filesName is a string[], it has been retrieve from an xml file Commented May 20, 2013 at 16:03

3 Answers 3

10

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.

answered May 20, 2013 at 16:04
Sign up to request clarification or add additional context in comments.

2 Comments

@Jim How so? "appname.exe.config".Split('.') == new [] { "appname", "exe", "config" }; the last element of that is "config", as expected.
@kevingessner Oops, overlooked your .Last...was going by the .Skip
1
fileNames.Select(s => Path.GetExtension(s)).Select(e => string.IsNullOrEmpty(e) ? "unknown" : e);
answered May 20, 2013 at 16:04

1 Comment

Path.GetExtension includes the leading "." on the extension -- you'll want to strip that off to get the desired result.
1

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.

answered May 20, 2013 at 16:06

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.