Laurence
Laurence

Reputation: 7823

How to validate rows in a datatable using few keywords asp.net

Dim keywords() As String = {"FirstName", "LastName", "Gender"}

I have a datatable with just 1 column. I want to check if all the rows in the datatable contain all of the keywords, For example,

    Table1
    __________
    FirstName
    LastName
    Gender

This table1 is valid.

    Table2
     ______
     FirstName
     Gender

This table2 is not valid coz LastName is missing

     Table3
      ______
      FirstName
      LastName
      Gender
      DateofBirth

This table3 is also valid coz it contains all the neccessary thing in the keyword. How can I do that ? Is it also possible to point out which is missing ? for example, in table2, LastName is missing.

Value added help would be .. check for duplicate as well .. but this is not essential .. if i can work out the first problem .. i am so grateful already ..

Thanks a lot ....

Upvotes: 0

Views: 868

Answers (2)

Firoz Ansari
Firoz Ansari

Reputation: 2515

Simply rotate a loop to DataTable rows

DataTable table = new DataTable();
// TODO: Render table

string[] keywords = { "FirstName", "LastName", "Gender" };
bool isValid = true;
bool hasDuplicates = false;
foreach (string keyword in keywords)
{
    DataRow[] rows = table.Select("Field='" + keyword + "'");
    if (rows.Count() <= 0)
    {
        isValid = false;
        break;
    }
    if (rows.Count() > 1)
    {
        hasDuplicates = true;
        break;
    }
}

if (!isValid)
{
    //TODO:
}
if (hasDuplicates)
{
    //TODO:
}

Upvotes: 1

SLaks
SLaks

Reputation: 887867

You can use LINQ:

var tableValues = table.AsEnumerable()
                       .Select(dr => dr.Field<String>("SomeColumn"))
                       .ToList();

if (keywords.Except(tableValues).Any()) {
    //Uh oh...
}

if (tableValues.Distinct().Count() < tableValues.Count) {
    //Uh oh...
}

Upvotes: 2

Related Questions