How can I make a DataTable enumerable?

I canโ€™t use AsEnumerable () in a DataTable, I use C # 3, but I just target framework 2.0 (LINQ is provided by LINQBridge ). Is there a way to make a DataTable enumerable without using Select ()?

bool isExisting = (bdsAttachments.DataSource as DataTable).Select().Any(xxx => (string)dr["filename"] == filename); 

Update:

I wanted it to look like this:

 bool isExisting = (bdsAttachments.DataSource as DataTable).AsEnumerable().Any(xxx => (string)dr["filename"] == filename); 

I get a suspicion that the Select DataTable method returns a copy, I think itโ€™s easy to use AsEnumerable, the problem is that I just target the 2.0 framework, System.Data.DataSetExtensions is not available

By the way, I tried this: http://cs.rthand.com/blogs/blog_with_righthand/archive/2006/01/15/284.aspx , but it has compilation errors.

+4
source share
4 answers
  public static IEnumerable<DataRow> EnumerateRows(this DataTable table) { foreach (var row in table.Rows) { yield return row; } } 

Lets you call:

 bool isExisting = (bdsAttachments.DataSource as DataTable).EnumerateRows().Any(dr => (string)dr["filename"] == filename); 
+11
source
  • IEnumerable<DataRow> rows = dataTable.AsEnumerable(); (System.Data.DataSetExtensions.dll)
  • IEnumerable<DataRow> rows = dataTable.Rows.OfType<DataRow>(); (System.Core.dll)
+4
source

Saving your enumerator strictly 2.0:

 public static IEnumerable<DataRow> getRows(DataTable table) { foreach (DataRow row in table.Rows) { yield return row; } } 

Then call with linqbridge as follows:

 bool isExisting = getRows(bdsAttachments.DataSource as DataTable).Any(row => (string)row["filename"] == filename); 
+2
source

You can try casting the DataTable as IEnumerable and iterate over the set:

 //your data exists as a DataTable DataTable dt = (DataTable)bdsAttachments.DataSource; foreach (DataRow row in dt) { if (row["filename"] == filename) return row; } 

The preview will go through the list and search for the file name (I assume that you are looking for the first DataRow with that file name, not all the strings matching the file name).

+1
source

Source: https://habr.com/ru/post/1286730/


All Articles