【问题标题】:Remove all duplicate numbers in ArrayList C#删除 ArrayList C# 中的所有重复数字
【发布时间】:2020-04-12 22:50:07
【问题描述】:

我对跟随代码有一些问题。我必须删除 ArrayList 中的所有重复数字并打印它们。例如:输入:11123345 输出:245。Т他的代码删除所有重复但留下其中之一:输入:11123345 输出:12345;

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        List<int> list = new List<int>();

        Console.WriteLine("Number: ");

        int num = int.Parse(Console.ReadLine());

        while (num > 0)
        {
            list.Add(num % 10);
            num /= 10;
        }

        list.Reverse();

        List<int> distinct = list.Distinct().ToList();

        PrintValues(distinct);

        static void PrintValues(IEnumerable distinct)
        {
            foreach (object value in distinct)
                Console.Write("{0}", value);
            Console.WriteLine();
        }
    }
}

【问题讨论】:

标签: c# arraylist


【解决方案1】:

我希望 Rad 的回答足以解决您的问题。

这是完整的工作代码:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        List<int> list = new List<int>();

        Console.WriteLine("Number: ");

        int num = int.Parse(Console.ReadLine());

        while (num > 0)
        {
            list.Add(num % 10);
            num /= 10;
        }

        list.Reverse();

            var distinct = list.GroupBy(x => x) 
                   .Where(y => y.Count() == 1) //It'll count numbers which have single number sequence like 1 2 3 ,etc. but for double number sequence like 22 33 44 ,etc. change Count() == 2                                            
                   .Select(y => y.Key).ToList();
            foreach (object value in distinct)
                Console.Write("{0}", value);
                Console.WriteLine();
                Console.ReadLine();
    }
}

【讨论】:

    【解决方案2】:

    假设 list 具有您要删除重复项的值,则此代码应该满足您的需求

    var distinct = list.GroupBy(x => x)         // Group by the items in the list
               .Where(g => g.Count() == 1)      // Filter only elements with a count of 1
               .Select(g => g.Key).ToList();    // Project them into a new list
    

    【讨论】:

      猜你喜欢
      • 2019-08-10
      • 1970-01-01
      • 1970-01-01
      • 2018-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-08
      • 2020-04-15
      相关资源
      最近更新 更多