集合的值去重复

因为用到list,要去除重复数据,尝试了几种方法。记录于此。。。

SQL语句去重复
select distinct(origin) from zw_text ;

测试数据:

List<string> li1 = new List<string> { "8", "8", "9", "9" ,"0","9"};
List<string> li2 = new List<string> {"张三","张三","李四","张三","王五","李四"};
List<string> li3 = new List<string> { "A", "A", "C", "A", "C", "D" };
List<string> li4 = new List<string> {"12","18","19","19","10","19"};

方法一:
HashSet<string> hs = new HashSet<string>(li1); //此时已经去掉重复的数据保存在hashset中

方法二:
for (int i = 0; i < li2.Count; i++)  //外循环是循环的次数
            {
                for (int j = li2.Count - 1 ; j > i; j--)  //内循环是 外循环一次比较的次数
                {

                    if (li2[i] == li2[j])
                    {
                        li2.RemoveAt(j);
                    }

                }
            }

方法三:
//把相同的用null代替。
for (int i = 0; i < li3.Count; i++){
    for (int j = 0; j < li3.Count; j++){
          if (i == j) continue;
                if (li3[i] == li3[j]){
                        li3[j] = "null";
                }
    }
}

方法四:
//这方法跟上面的一样,只是变了逻辑
for (int i = 0; i < li4.Count - 1; i++){
     for (int j = 0; j < li4.Count ; j++){
         if (i != j){
             if (li4[i] == li4[j]){
                 li4[j] = "null";
             }
         }
     }
}


如果你仅仅比较两个值是否相等
List<string> li1 = new List<string> { "8", "8", "9", "8", "0", "9" };
li1 = li1.Distinct().ToList();

你可能感兴趣的:(去重复)