Search code examples
c#vb.netlinqasenumerable

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.

jane@doe.com
mike@foo.com
donald@duck.com

And the current logged in user is harry@houdini.com. 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( "harry@houdini.com")

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

Thanks


Solution

  • Here is working example with DataTable as follows

    In C#

            DataTable dt = new DataTable();
            dt.Columns.Add("emails");
            dt.Rows.Add("jane@doe.com");
            dt.Rows.Add("mike@foo.com");
            dt.Rows.Add("donald@duck.com");
    
            var authorized = dt.AsEnumerable().Any(s => s[0].Equals("mike@foo.com")); //returns True
            var notAuthorized = dt.AsEnumerable().Any(s => s[0].Equals("harry@houdini.com"));  //returns False
    

    In VB (Converted online)

            Dim dt As DataTable = New DataTable
            dt.Columns.Add("emails")
            dt.Rows.Add("jane@doe.com")
            dt.Rows.Add("mike@foo.com")
            dt.Rows.Add("donald@duck.com")
            Dim authorized As var = dt.AsEnumerable.Any(() => {  }, 
               s(0).Equals("mike@foo.com"))
            Dim notAuthorized As var = dt.AsEnumerable.Any(() => {  }, 
               s(0).Equals("harry@houdini.com"))