Tim
Tim

Reputation: 8921

DataTable AsEnumerable matching a single value

Let's say my query returns a DataTable which is a list of email addresses, a single varchar column called "email"; these emails are authorized to do something.

[email protected]
[email protected]
[email protected]

And the current logged in user is [email protected]. He's not authorized. He's not on the list

Is it possible to iterate the DataRows using Linq and return a boolean false?

Or to return an object which is null or Nothing or empty?

In essence, I would like to know the Linq version of

 Authorized = List.Contains( "[email protected]")

I would really like to know how to do this both in C# and VB.

Thanks

Upvotes: 1

Views: 3009

Answers (2)

Ehsan Ullah Nazir
Ehsan Ullah Nazir

Reputation: 1917

Here is working example with DataTable as follows

In C#

        DataTable dt = new DataTable();
        dt.Columns.Add("emails");
        dt.Rows.Add("[email protected]");
        dt.Rows.Add("[email protected]");
        dt.Rows.Add("[email protected]");

        var authorized = dt.AsEnumerable().Any(s => s[0].Equals("[email protected]")); //returns True
        var notAuthorized = dt.AsEnumerable().Any(s => s[0].Equals("[email protected]"));  //returns False

In VB (Converted online)

        Dim dt As DataTable = New DataTable
        dt.Columns.Add("emails")
        dt.Rows.Add("[email protected]")
        dt.Rows.Add("[email protected]")
        dt.Rows.Add("[email protected]")
        Dim authorized As var = dt.AsEnumerable.Any(() => {  }, 
           s(0).Equals("[email protected]"))
        Dim notAuthorized As var = dt.AsEnumerable.Any(() => {  }, 
           s(0).Equals("[email protected]"))

Upvotes: 2

D Stanley
D Stanley

Reputation: 152566

Any is probably cleaner here:

bool exists = dataTable.AsEnumerable()
                       .Any(r => "[email protected]".Equals(r[0]));

You could project the column to a collection of strings and use Contains, but it seems like overkill here.

Or define a primary key and use the native Contains method on DataRowCollection:

dataTable.PrimaryKey = dataTable.Columns[0];
bool exists = dataTable.Rows.Contains("[email protected]");

Upvotes: 2

Related Questions