You can tweak the solution to make to suit your needs!
One possible solution is using the following snippet.
public static class ListExtensions
{
public static bool Add<T>(this List<T> List, T item)
{
bool isAdded = false;
if (!List.Contains(item))
{
List.Add(item);
isAdded = true;
}
return isAdded;
}
public static string ToStringEx(this string[] StringArray)
{
StringBuilder stringBuilder = new StringBuilder();
foreach (string stringItem in StringArray)
{
stringBuilder.AppendFormat("{0},", stringItem);
}
return stringBuilder != null ? stringBuilder.ToString().TrimEnd (new char[] {','}) : string.Empty;
}
}
public class Program
{
static void Main()
{
List<string> stringList = null;
string longString = null;
string[] stringArray = null;
try
{
stringList = new List<string>();
longString = "BOOK,COOK,BOOK,COOK,BOOK,LOOK,COOK,COOK,BOOK";
stringArray = longString.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
foreach (string stringItem in stringArray)
{
stringList.Add<string>(stringItem);
}
stringArray = stringList.ToArray();
longString = stringArray.ToStringEx();
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace);
}
Console.ReadKey();
}
Or you can stip the code from the extension methods and use inline -
static void Main()
{
List<string> stringList = null;
string longString = null;
string[] stringArray = null;
StringBuilder stringBuilder = null;
try
{
stringList = new List<string>();
longString = "BOOK,COOK,BOOK,COOK,BOOK,LOOK,COOK,COOK,BOOK";
stringArray = longString.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
foreach (string stringItem in stringArray)
{
if (!stringList.Contains(stringItem))
{
stringList.Add(stringItem);
}
}
stringArray = stringList.ToArray();
stringBuilder = new StringBuilder();
foreach (string stringItem in stringArray)
{
stringBuilder.AppendFormat("{0},", stringItem);
}
longString = stringBuilder.ToString();
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace);
}
Console.ReadKey();
}
Regards,
ErSehmi