How can I make DataTable enumerable?

£可爱£侵袭症+ 提交于 2019-12-21 17:39:21

问题


I cannot use AsEnumerable() on DataTable, I'm using C# 3 but I'm just targeting 2.0 framework (LINQ capability is courtesy of LINQBridge). Is there any way I can make DataTable enumerable without using Select() ?

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

Update:

I wanted it to make it look like this:

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

I'm getting an inkling that the Select method of DataTable returns a copy, I'm thinking to just use AsEnumerable, the problem is I'm just targeting 2.0 framework, System.Data.DataSetExtensions is not available

BTW, i tried this: http://cs.rthand.com/blogs/blog_with_righthand/archive/2006/01/15/284.aspx, but has compilation errors.


回答1:


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

Allows you to call:

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



回答2:


  1. IEnumerable<DataRow> rows = dataTable.AsEnumerable(); (System.Data.DataSetExtensions.dll)
  2. IEnumerable<DataRow> rows = dataTable.Rows.OfType<DataRow>(); (System.Core.dll)



回答3:


Keeping 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 like this:

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



回答4:


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 foreach will iterate through the list and search of the filename (I assume you're searching for the first DataRow with that filename, not all rows that match the filename).



来源:https://stackoverflow.com/questions/1041955/how-can-i-make-datatable-enumerable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!