阿里云折扣码

轻云博客 > Asp .net网站开发 > c#过滤字符串中相同的字符串只保留一个

c#过滤字符串中相同的字符串只保留一个

作者:Aisencici / 日期:2014-5-14 16:57:00 / 分类:Asp .net网站开发 / 浏览:2236

方法一,原生态:调用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;

    }


本文标签:过滤字符串
From:Aisencici
分享到: