首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

List<int> a = new List<int>(); 怎么删除a中的重复元素

2012-01-10 
Listint a new Listint() 如何删除a中的重复元素Listint a new Listint() 如何删除a中的重

List<int> a = new List<int>(); 如何删除a中的重复元素
List<int> a = new List<int>(); 如何删除a中的重复元素

[解决办法]

C# code
static void Main(string[] args)        {            List<int> a = new List<int>();            a.Add(1);            a.Add(1);            a.Add(4);            a.Add(3);            List<int> newList = new List<int>();            foreach (int i in a)            {                if (!newList.Contains(i))                {                    newList.Add(i);                }            }            foreach (int i in newList)            {                Console.WriteLine(i.ToString());            }                Console.ReadKey();        }
[解决办法]
List<int> a = new List<int>();
int n;
a.Add(1);
a.Add(2);
a.Add(3);
a.Add(3);
a.Add(2);
a.Add(2);
a.Add(2);
a.Add(3);
n = a.Count;
for (int i = 0; i < n-1; i++)
{
for (int j = i + 1; j < n; )
{
if (a[j] == a[i])
{
a.RemoveAt(j);
--n;
}
else
{
++j;
}
}
}

foreach (int i in a)
{
Console.WriteLine(i);
}[code=C#][/code]
[解决办法]
C# code
            List<int> list = new List<int>() { 1, 2, 2, 3, 4, 2, 4, 3, 1 };            list = list.Distinct().ToList();            //以上为C#3.0版本以上可用            //以下为C#2.0可用            List<int> a = new List<int>();            a.Add(1);            a.Add(2);            a.Add(3);            a.Add(3);            a.Add(2);            a.Add(2);            a.Add(2);            a.Add(3);            for (int i = a.Count - 1; i >= 0; i--)                if (a.IndexOf(a[i]) != i)                    a.RemoveAt(i);            foreach (int i in a)                Console.WriteLine(i);
[解决办法]
和4,5楼一样,只是简化些,易看些 ;
 1楼也不错;
 3楼在C# 下我没有找到同名方法,或许有其它类似的,我不知道;
 private static void ListDuplicate()
{
List<int> listInt = new List<int>(100);
listInt .Add(1);
listInt .Add(2);
listInt .Add(3);
listInt .Add(3);

for (int i = 0; i < listInt.Count; i++)
{
for (int j =i+ 1; j < listInt.Count; j++)
{
if (listInt[i] == listInt[j])
{
listInt.RemoveAt(j);

j--;
}
}
}

}

热点排行