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));
我想制作一个新列表,其中包括 Allnumber 列表中的 3 个。 它应该包含所有具有 3 的数字(3、13、23、33、34、36、39、43、53 ...)。 无论如何只拿起3s? 我发现有 Findall、Contain 方法,但不能将其用于 int 类型列表。谢谢大家 不敢相信有这么多方法可以做到这一点 :D
最佳答案
我会将此检查移至单独的方法
public static bool ContainsDigit(int input, int digit)
{
do
{
if (input % 10 == digit)
{
return true;
}
input /= 10;
}
while (input > 0);
return false;
}
用法:
List<int> result = Allnumber.Where(x => ContainsDigit(x, 3)).ToList();
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();
性能(1000000
个数字的所有数字):
|------------------------------------------------------|
| 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 并不能真正与 benachmarking 一起工作 - 它每次运行都会有所不同,可能是因为 dotnetfiddle 的负载,我只能使用 100,000
而不是 1,000,000
数字但是... https://dotnetfiddle.net/pqCx2J
关于C# 如何从列表中提取包含 x 数字的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49810689/