list add前判断是否有重复字符串

tingsicheng3316 2016-12-19 10:52:10

List<string> s2= new List<string>();
private void textBox1_MouseLeave(object sender, EventArgs e)
{
filtim = textBox1.Text;
string text = "FILTIM" + " " + filtim;
s2.Add(text);

}
想修改成add之前,测试s2中的string是否已经indexof FILTIM,如果没有的话,执行add,有的话,将原先indexof FILTIM 的string用新的text替换
...全文
298 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
threenewbee 2016-12-20
  • 打赏
  • 举报
回复
if (s2.Contains( textBox1.Text)) // 已经存在
crystal_lz 2016-12-20
  • 打赏
  • 举报
回复

Dictionary<string, string> dic = new ...
if(dic.Contains("F..."))
dic["F.."] = "new text";
else
dic.Add("F..","text");
混QWER 2016-12-20
  • 打赏
  • 举报
回复
引用 6 楼 tingsicheng3316 的回复:
[quote=引用 3 楼 diaodiaop 的回复:]

  filtim = textBox1.Text;
  string text = "FILTIM" + " " + filtim;
  if (!s2.Contains(text ))
 {
    s2.Add(text);
 }
 
                    
private void textBox1_MouseLeave(object sender, EventArgs e) { filtim = textBox1.Text; string text = "FILTIM" + " " + filtim; if (s2.Count == 0) s2.Add(text); else { foreach (string str in s2) { if (!str.Contains("FILTIM")) { s2.Add(text); } } } } 我要判断有没有FILTIM ,不是text. 当我的textbox里的值改变的时候,是不是s2中的text也跟着改变,但是我现在这样写,s2没有改变[/quote]
 private void textBox1_MouseLeave(object sender, EventArgs e)
        {
            filtim = textBox1.Text;
            string text = "FILTIM" + " " + filtim;
            bool exist = false;
            if (s2.Count == 0)
                s2.Add(text);
            else
            {
                for (int i = 0; i < s2.Count; i++)
                {
                    if (s2[i].IndexOf("FILTIM") > -1)
                    {
                        s2[i] = text;
                        exist = true;
                    }
                }
            }
            if (!exist)
            {
                s2.Add(text);
            }
        }
tingsicheng3316 2016-12-20
  • 打赏
  • 举报
回复
引用 3 楼 diaodiaop 的回复:

  filtim = textBox1.Text;
  string text = "FILTIM" + " " + filtim;
  if (!s2.Contains(text ))
 {
    s2.Add(text);
 }
 
                    
private void textBox1_MouseLeave(object sender, EventArgs e) { filtim = textBox1.Text; string text = "FILTIM" + " " + filtim; if (s2.Count == 0) s2.Add(text); else { foreach (string str in s2) { if (!str.Contains("FILTIM")) { s2.Add(text); } } } } 我要判断有没有FILTIM ,不是text. 当我的textbox里的值改变的时候,是不是s2中的text也跟着改变,但是我现在这样写,s2没有改变
  • 打赏
  • 举报
回复
HashSet<T>用于按插入顺序排列但值唯一的 SortedSet<T>用于需要排序但值唯一的
正怒月神 2016-12-20
  • 打赏
  • 举报
回复
s2.Contains
by_封爱 版主 2016-12-20
  • 打赏
  • 举报
回复

  filtim = textBox1.Text;
  string text = "FILTIM" + " " + filtim;
  if (!s2.Contains(text ))
 {
    s2.Add(text);
 }
 
                    
  • 打赏
  • 举报
回复
恩,相信8楼的,用Dictionary吧。
Poopaye 2016-12-19
  • 打赏
  • 举报
回复
你应该用hashset

110,525

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧