2017-07-29 73 views
-2

問題已解決,代碼在解釋其嘗試實現的內容之後。從列表中選擇<string>

的代碼應該能夠檢索數量重演

首先的次數,代碼試圖從用戶那裏得到一個數字: 例如:「221132」

之後,用戶輸入一個數字,程序找到該數字包含在他的第一個輸入中的次數。

例如:「2」應該返回數字3,因爲這是在第一個輸入中使用該數字的次數。

注:我想插入那些爲List<T>,並從那裏來算,但:

  • 我不能使用List(T).Count之間的財產。

  • 我必須使用.FindAll使用LINQ

static void Main(string[] args) 
    { 
     Console.WriteLine("Please enter a number"); 
     string InputNo = Console.ReadLine(); 

     List<char> result = InputNo.ToList(); 
     var strResult = result.Select(p => p.ToString()).ToList(); 

     Console.WriteLine("Type the number you want to find and how many times it is repeated"); 
     string findOccurence = Console.ReadLine(); 

     var found = strResult.FindAll(p => p == findOccurence); 

     int counterOfRepeats = 0; 

     var intFound = found.ConvertAll(p => Convert.ToInt32(p)); 

     for (int i = 0; i < InputNo.Length; i++) 
     { 
      try 
      { 

       counterOfRepeats++; 
      } 
      catch (Exception) 
      { 

       throw; 
      } 
     } 


     Console.WriteLine(counterOfRepeats); 
     Console.ReadLine(); 
    } 

注:此代碼計數串重演的次數,而無需使用.Count之間

回答

0

FindAll返回一個List。

var found = strResult.FindAll(p => p== findOccurence).Count; 
2

我知道你說你不能使用Count財產,怎麼樣的LINQ的Count()方法:您可以通過檢查Count屬性得到返回的列表項的數目?

var found = strResult.Count(p => p == findOccurence); 
0

您也可避免lambda表達式:

int found = InputNo.ToList().FindAll(findOccurence[0].Equals).Count;