How can I replace ConvertListToString(extensions)
with an elegant LINQ statement?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestExtn2343
{
class Program
{
public static void Main(string[] args)
{
string[] files = { "test.txt", "test2.txt",
"test.as", "notes.doc",
"data.xml", "test.xml",
"test.html", "notes.txt",
"test.xls" };
List<string> extensions = (from file in files
let index = file.LastIndexOf('.') + 1
select file.Substring(index)).Distinct().ToList<string>();
Console.WriteLine("The kinds of file extensions used are {0}.", ConvertListToString(extensions));
Console.ReadLine();
}
public static string ConvertListToString(List<string> list) {
StringBuilder sb = new StringBuilder();
int count = 1;
foreach (var listItem in list)
{
sb.Append(listItem.ToUpper());
if (count != list.Count)
sb.Append(", ");
count++;
}
return sb.ToString();
}
}
}