2011-03-09 266 views
29

我有一個數據表dtFoo,並希望獲得滿足特定條件的行數。獲取數據表中符合特定條件的行數

編輯:此數據不存儲在數據庫中,因此使用SQL不是一個選項。

在過去,我用以下兩種方法來實現:

方法1

int numberOfRecords = 0; 
DataRow[] rows; 

rows = dtFoo.Select("IsActive = 'Y'"); 
numberOfRecords = rows.Length; 

Console.WriteLine("Count: " + numberOfRecords.ToString()); 

方法2

int numberOfRecords = 0; 

foreach (DataRow row in dtFoo.Rows) 
{ 
    if (row["IsActive"].ToString() == "Y") 
    { 
     numberOfRecords++; 
    } 
} 

Console.WriteLine("Count: " + numberOfRecords.ToString()); 

我的店是試圖在一些事情上標準化,這是一個已經出現的問題。我想知道哪些方法在性能(以及爲什麼!)方面最好,以及最常用的方法。

另外,是否有更好的方法來達到預期的效果?

回答

50

一個簡單的方法來完成這個合併什麼被張貼在原崗位到一個單一的語句:

int numberOfRecords = dtFoo.Select("IsActive = 'Y'").Length; 

另一種方式來完成,這是使用LINQ方法:

int numberOfRecords = dtFoo.AsEnumerable().Where(x => x["IsActive"].ToString() == "Y").ToList().Count; 

注意這需要包括System.Linq

+1

優秀的解決方案,你可以讓我知道一些來源,我可以看到許多LINQ的例子嗎? – 2014-03-29 14:21:27

+0

@Saluce,dtFoo.AsEnumerable()。where(expr)does not need to convert enumerable as we can use dtFoo.Where(expr)is already enumerable – 2015-07-14 11:53:54

+1

@Sunny_Sid這是不正確的。你必須明確地轉換爲'Enumerable'來使用'Enumerable.Where'。 – saluce 2015-10-08 13:58:22

0

如果數據存儲在數據庫中,將查詢發送到數據庫會更快,而不是獲取所有數據並在內存中查詢它。

做到這一點的第三種方法是LINQ到數據集,但我懷疑這三種方法在性能上差異很大。

+0

此數據不存儲在數據庫中。我編輯了我的原始條目以反映這一點。 – Sesame 2011-03-10 16:37:22

2

不知道這是快,但至少它的短:)

int rows = new DataView(dtFoo, "IsActive = 'Y'", "IsActive", 
    DataViewRowState.CurrentRows).Table.Rows.Count; 
+0

int rows = new DataView(dtFoo,「IsActive ='Y'」,「IsActive」, DataViewRowState.CurrentRows).Table.Rows.Count;'short than'int rows = dtFoo.Select(「IsActive = 'Y'「)長度。'? – PedroC88 2013-07-04 05:15:59

+0

@ PedroC88:不是;它比原始海報的方法短。 – Cosmin 2013-07-04 09:42:56

3
int numberOfRecords = 0; 

numberOfRecords = dtFoo.Select().Length; 

MessageBox.Show(numberOfRecords.ToString()); 
+2

@Sesame已經描述過dtFoo.Select方法。此外,問題是關於按某些標準計算,而不是檢索記錄總數。 – Alexander 2014-04-30 12:48:10

+0

對我有幫助謝謝 – 2016-03-28 04:40:03

0
object count =dtFoo.Compute("count(IsActive)", "IsActive='Y'"); 
5
int numberOfRecords = DTb.Rows.Count; 
int numberOfColumns = DTb.Columns.Count; 
1

試試這個

int numberOfRecords = dtFoo.Select("IsActive = 'Y'").Count<DataRow>();  
Console.WriteLine("Count: " + numberOfRecords.ToString()); 
相關問題