Accepted answer
var s = string.join(", ", => path.getextension(file))


how about this:

string output = string.join(", ",(from file in files
  let index = file.lastindexof('.') + 1
  select file.substring(index)).distinct().toarray<string>());


how about this...

public static string convertlisttostring(list<string> list) 
    return list.aggregate((x, y) => x + ", " + y).toupper();

this does it in one line, and i've moved the "toupper" out onto the final string so it's only called once.

clearly you could then throw away the method convertlisttostring and inline if you wanted.


here's how:

string s = string.join(", ", (from extension in extensions select extension.toupper()).toarray());

note, i would probably not write this as one line, rather like this:

string s = string.join(", ",
    (from extension in extensions
     select extension.toupper()).toarray());

if you don't mind just going for the linq extension methods directly, instead of the linq query syntax, you can use this:

string s = string.join(", ", => e.toupper()).toarray());

another variant would be to just call toupper on the final string instead:

string s = string.join(", ", extensions.toarray()).toupper();

and finally, in .net 4.0, string.join finally supports ienumerable<string> directly, so this is possible:

string s = string.join(", ", extensions).toupper();

note that per your question, this might lead to duplicates nonetheless. consider what would happen if your original list of filenames contained both "filename.txt" and "filename.txt", these would be counted as two distinct extensions.

the call to toupper should be moved up before the call to distinct to fix this.

instead of the original linq expression + code, i would rewrite the whole thing to this:

string[] distinctextensions = files
    .select(filename => path.getextension(filename).toupper())
string distinctextensionsasstring = string.join(", ", distinctextensions);

if you add the following utility method to your code library, you can simplify it further:

public static class stringextensions
    public static string join(this ienumerable<string> elements, string separator)
        if (elements is string[])
            return string.join(separator, (string[])elements);
            return string.join(separator, elements.toarray());

and then your code can look like this:

string distinctextensionsasstring = files
    .select(filename => path.getextension(filename).toupper())
    .join(", ");

Related Query