2016-11-15 57 views
0

在int []或double []的數組中,我們可以使用indexOf來查找特定值/對象的索引。但不是dateTime []數組的情況。如何在日期數組中找到特定日期的索引?在dateTimeArray中查找指定日期的索引

using System; 
using System.Linq; 
using System.Windows.Forms; 

namespace WindowsFormsApplication1 
{ 
public partial class Form1 : Form 
{ 
    public Form1() 
    { 
     InitializeComponent(); 

     DateTime[] myDates = new DateTime[10]; 
     int index = 0; 

     for(int i=0;i<10;i++) 
     {myDates[i] = new DateTime(2016, 10, i + 1);} 
    } 
} 
} 

這裏我試圖找到索引

//Find the index of October 7,2016 
     DateTime dateTimeFindIndex = new DateTime(2016, 10, 7); 
     for (int i = 0; i < 10; i++) 
     { 
      if(dateTimeFindIndex==myDates[i]) 
      { 
       index = i; 
       break; 
      } 

     } 

是否有更好的方法來做到這一點?

回答

0

您可以使用Array.IndexOf

var ind = Array.IndexOf(myDates,dateTimeFindIndex);