c#过滤字符串中相同的字符串只保留一个
方法一,原生态:调用filterRepeatChar( "朱雅君,姚怡尔,涂静,涂静,刘刚,姚怡尔")
public static string filterRepeatChar(string _val)
{
string _str = string.Empty;
string[] strArray = _val.Split(',');
for (int i = 0; i < strArray.Length; i++)
{
for (int j = i + 1; j < strArray.Length; j++)
{
if (strArray[j] == strArray[i])
{
strArray[i] = string.Empty;
}
}
if (strArray[i] != string.Empty)
_str += strArray[i] + ",";
}
if (_str.LastIndexOf(",") > -1)
_str = _str.Substring(0, _str.Length - 1);
return _str;
}
方法二,用linq实现filterRepeatCharToLinq("朱雅君,姚怡尔,涂静,涂静,刘刚,姚怡尔s")
public static string filterRepeatCharToLinq(string _val)
{
var wq = from p in _val.Split(',').Distinct()
select p;
string rw = "";
foreach (var kk in wq)
{
rw += kk.ToString() + ",";
}
rw = rw.TrimEnd(',');
return rw;
}