string temp=",309,309,310,310,310,310,310,310,311,311,311";为原字串
要求处理结果为:,309,310,311,
string timetemp = null;
string temp=",309,309,310,310,310,310,310,310,311,311,311";
string[] str = temp.Split(",".ToCharArray());
String[] str1 = { "" };
System.Collections.Specialized.StringCollection sc = new System.Collections.Specialized.StringCollection();
sc.AddRange(str1);
foreach (string s in str)
{
if (!sc.Contains(s))
{
sc.Add(s);
}
}
String[] str2 = new string[sc.Count];
sc.CopyTo(str2, 0);
foreach (string ss in str2)
{
timetemp +=","+ss;
Console.WriteLine(ss);
}
timetemp= timetemp.Insert(timetemp.Length, ",");
timetemp = timetemp.Remove(0,1);
还有个更简洁的方法
string timetemp = null;
string temp=",309,309,310,310,310,310,310,310,311,311,311";
string[] str = temp.Split(",".ToCharArray());
String[] str1 = { "" };
string[] str2 = str.Union(str1).Distinct().ToArray();
foreach (string s in str2)
{
timetemp += "," + s;
}
timetemp = timetemp.Insert(timetemp.Length, ",");
timetemp = timetemp.Remove(0, 1);
Console.WriteLine(timetemp);