How to use Contains using C #

I have a DataTable with a primary key with multiple columns

dt.PrimaryKey = new DataColumn[] {dt.Columns["Name"], dt.Columns["Type"] };

      

Now I want to check if my DataTable contains dt (Adarsh, Developer)

I need to pass two values ​​to Contains Method

I tried using the following which doesn't seem to work

DataRow dr = dt.Rows(e.RowIndex); 
DataRow drNew = dt.NewRow();
drNew["Name"] = dr["Name"];
drNew["Type"] = dr["Type"];
drNew["Address"] = dr["Address"];

if(dt.Rows.Contains(drNew["Name"].ToString(), drNew["Type"].ToString())) //This gives me an error
{
}

      

thanks in advance

+3


source to share


2 answers


The overload DataRowCollection.Contains

has one parameter:, Object[] keys

but you are trying to pass two arguments.

You need to wrap your keys in Object[]

:

dt.Rows.Contains(new object[]{first_value, second_value})

      




If you find it ugly, you can wrap it up with a simple extension method like this:

public static class Extenstions
{
    public static bool Contains(this DataRowCollection c, params object[] args)
    {
        return c.Contains(args);
    }
}

      

which will allow you to call it the way you do, like

dt.Rows.Contains(first_value, second_value)

      

+7


source


You can try Select ().

DataRow[] result = table.Select("Name = 'foo' and Type = 'bar'");

      



And then see if the result is greater than 0.

+1


source







All Articles