private static readonly List<long> KnownPrimes = new List<long>() { 2, 3, 5, 7};
static void Main(string[] args)
{
int numDivisors;
string input = "";
bool first = true;
while (!int.TryParse(input, out numDivisors))
{
if(!first) Console.WriteLine("You must enter a number with no other characters.");
Console.WriteLine("Find the least common multiple for numbers 1 through:");
input = Console.ReadLine();
first = false;
}
int index = -1;
//make sure that there are enough primes in the list
while (index == -1)
{
index = KnownPrimes.FindIndex(n => n > numDivisors);
if(index == -1) AppendNextPrime();
}
// prep the list with 0s
List<int> countPrimes = KnownPrimes.Select(n=>0) as List<int>;
當我在 Rider 中除錯最后一行時,它顯示:
Enumerable.Select() returned: Count = 5 countPrimes: null
從我讀過的內容來看,LINQ 不應該能夠回傳空值,而且它似乎不是,但不知何故,變數仍然是空值。我顯然在這里遺漏了一些東西,誰能幫我確定我做錯了什么?
uj5u.com熱心網友回復:
as 運算子將回傳 null,因為 Select 的結果不是List<int>,而是IEnumerable<int>. 將其替換ToList為從 IEnumerable 中創建一個串列:
List<int> countPrimes = KnownPrimes.Select(n=>0).ToList();
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/494215.html
下一篇:使用LINQ從檔案中選擇未知值
