Pretty simple use of linq:
public static string SupportedFilesToDisplayString(string supportedFileTypes)
{
if (supportedFileTypes == null)
{
throw new ArgumentNullException("supportedFileTypes");
}
var fileTypes = supportedFileTypes.Split('|')
.Select(s => string.Format("\"{0}\"", s));
var lastFileType = fileTypes.Skip(fileTypes.Count() - 1).SingleOrDefault();
var otherFileTypes = fileTypes.Take(fileTypes.Count() - 1);
if (otherFileTypes.Any())
{
var otherString = String.Join(", ", otherFileTypes.ToArray());
return string.Format("{0} and {1}", otherString, lastFileType);
}
else
{
return lastFileType;
}
}
Small test in the Snippet compiler:
public static void RunSnippet()
{
WL(SupportedFilesToDisplayString(".jpg|.gif|.png"));
WL(SupportedFilesToDisplayString(".jpg|.png"));
WL(SupportedFilesToDisplayString(".png"));
WL(SupportedFilesToDisplayString(""));
WL(SupportedFilesToDisplayString(null));
}
Display:
".jpg", ".gif" and ".png"
".jpg", ".gif" and ".png"
".jpg" and ".png"
".png"
""
---
The following error occurred while executing the snippet:
System.ArgumentNullException: Value cannot be null.
Parameter name: supportedFileTypes
at MyClass.SupportedFilesToDisplayString(String supportedFileTypes)
at MyClass.RunSnippet()
at MyClass.Main()
---
source
share