从列表C#中删除重复值的方法

时间:2014-11-16 17:26:31

标签: c# list

我见过其他人有类似的问题,但没有任何解决方案可以帮助我。

我正在寻找一种方法:

List<int> Factors = new List<int> {2, 5, 5, 7, 2, 3};

返回:

{7, 3};

有什么方法可以做到这一点吗?

2 个答案:

答案 0 :(得分:9)

使用GroupBy,您可以对数字进行分组,并获得只有一个数字的组:

Factors = Factors.GroupBy(x => x)
   .Where(g => g.Count() == 1)
   .Select(g => g.Key)
   .ToList();

答案 1 :(得分:0)

可能是非LINQ解决方案。将列表中的数字key添加到哈希表中。在下一次迭代中,如果在哈希表中找到相同的键,则增加它的相应值。所以,最后你将只留下那些只有一个外观的数字。

    static void Main(string[] args)
    {
        List<int> Factors = new List<int> { 2, 5, 5, 7, 2, 3, 2, 9, 8, 9, 11, 9, 12, 9, 13, 9 };
        Hashtable ht = new Hashtable();
        foreach (var item in Factors)
        {
            if (ht.ContainsKey(item))
            {
                ht[item] = Convert.ToInt32(ht[item]) + 1;
            }
            else
                ht.Add(item, 1);
        }

        foreach (var item in ht.Keys)
        {
            if (Convert.ToInt32(ht[item]) == 1)
            Console.WriteLine(item.ToString());
        }
    }
相关问题