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.

[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


Solution

  • 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]"))