如何使用 C# 使用 Contains

How to use Contains using C#

我有一个包含多列主键的 DataTable

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

现在我想检查我的 DataTable dt 是否包含 (Adarsh, Developer)

我必须在 Contains 方法中传递两个值

我尝试使用以下方法,但似乎不起作用

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
{
}

提前致谢

您可以尝试 Select()。

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

然后查看结果计数是否大于 0。

您要使用的 DataRowCollection.Contains 重载只有一个参数:Object[] keys,但您试图传递两个参数。

您必须将密钥打包成 Object[]:

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

如果你觉得它很丑,你可以用这样一个简单的扩展方法来包装它:

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

这将使您能够按照自己的方式调用它,例如

dt.Rows.Contains(first_value, second_value)

LINQ 更容易实现非常相似的结果

string name = "Bill";
bool hasValue = dt.AsEnumerable().Any(row => 'value' == row.Field<String>("Name"));

..也可以在这里找到一个非常相似的问题 Check if value exists in dataTable?