C#如何从List中获取包含x编号的数字?

Jun*_*Koo 4 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));
Run Code Online (Sandbox Code Playgroud)

我想制作一个新列表,其中包括来自Allnumber列表的3个.它应该包含所有具有3(3,13,23,33,34,36,39,43,53 ......)的数字.无论如何只拿3s?我发现有Findall,Contain方法但不能用于int类型列表.谢谢你们每个人都不能相信有这么多方法可以做到:D

fub*_*ubo 8

我会将此签入移至单独的方法

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

用法:

List<int> result = Allnumber.Where(x => ContainsDigit(x, 3)).ToList();
Run Code Online (Sandbox Code Playgroud)

https://dotnetfiddle.net/2ZPNbM


一行中的方法相同

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();
Run Code Online (Sandbox Code Playgroud)

性能(Allnumber with 1000000numbers):

|------------------------------------------------------|
| 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 |
|------------------------------------------------------|
Run Code Online (Sandbox Code Playgroud)

dotnetfiddle并不真正适用于benachmarking - 每次运行都有所不同,可能是因为dotnetfiddle的负载,我只能使用100,000而不是1,000,000数字但是... https://dotnetfiddle.net/pqCx2J

  • 在我的答案中支持这一点,随着列表的增加,我的逐渐变慢.它的不明显与100,000,但非常显着1,000,000.不要做字符串操作的孩子! (2认同)