Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# How can I pick up numbers that contains x number from List?

Tags:

c#

list

    static void Main(string[] args)
    {
        List<int> Allnumber = new List<int>();
        Random rnd = new Random();
        while (true)
        {
            int dice = rnd.Next(1, 100);
            Console.WriteLine("Random number between 1 and 100 : {0}", dice);
            Allnumber.Add(dice);
            if (dice == 1)
                break;
        }

        Console.WriteLine();
        Console.WriteLine("Allnumber : " + string.Join(" ", Allnumber));
        List<int> Odd = (from number in Allnumber where number % 2 != 0 select number).ToList();
        List<int> Even = new List<int>(from number in Allnumber where number % 2 == 0 select number);
        Console.WriteLine("Odd : " + string.Join(" ", Odd));
        Console.WriteLine("Even : " + string.Join(" ", Even));

I want to make a new list which includes 3 from Allnumber list. It should be containing all the number that has 3(3, 13, 23, 33, 34, 36, 39, 43, 53...). Anyway to pick up only 3s? I found out there are Findall, Contain methods but cant use it for int type list. THANK YOU EVERYONE cant believe that there are so many ways to do it :D

like image 420
Jungmin Koo Avatar asked Dec 07 '22 15:12

Jungmin Koo


1 Answers

I would move this check in to a separate method

public static bool ContainsDigit(int input, int digit)
{
    do
    {
        if (input % 10 == digit)
        {
            return true;
        }
        input /= 10;
    }
    while (input > 0);
    return false;
}

usage:

List<int> result = Allnumber.Where(x => ContainsDigit(x, 3)).ToList();

https://dotnetfiddle.net/2ZPNbM


Same approach in one line

List<int> Allnumber = Enumerable.Range(0, 100).ToList();
List<int> result = Allnumber.Where(x => { do { if (x % 10 == 3) return true; } while ((x /= 10) > 0); return false; }).ToList();

Performace (Allnumber with 1000000 numbers):

|------------------------------------------------------|
| User       | Method                   | Time         |
|------------|--------------------------+--------------|
| fubo       | ContainsDigit()          | 0,03 seconds |
| JamieC     | ToString().Contains("3") | 0,20 seconds |
| TheGeneral | WhereDigit()             | 0,10 seconds |
| TheGeneral | InternalRun()            | 0,04 seconds |
|------------------------------------------------------|

dotnetfiddle doesn't really work with benachmarking - it varies a bit each run probably because of the load of dotnetfiddle and I can only use 100,000 instead of 1,000,000 numbers but ... https://dotnetfiddle.net/pqCx2J

like image 153
fubo Avatar answered May 21 '23 06:05

fubo