C# 如何检查数据表中是否存在列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17706326/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if a column exists in a datatable
提问by Rémi
I have a datable generated with the content of a csv file. I use other information to map some column of the csv (now in the datatable) to information the user is required to fill.
我有一个用 csv 文件的内容生成的数据。我使用其他信息将 csv 的某些列(现在在数据表中)映射到用户需要填写的信息。
In the best world the mapping would be alway possible. But this is not reality... So before I try to map the datatable column value I would need to check if that column even exist. If I don't do this check I have an ArgumentException.
在最好的世界中,映射总是可能的。但这不是现实......所以在我尝试映射数据表列值之前,我需要检查该列是否存在。如果我不做这个检查,我就会有一个 ArgumentException。
Of course I can check this with some code like this :
当然,我可以用一些这样的代码来检查这个:
try
{
//try to map here.
}
catch (ArgumentException)
{ }
but I have for now 3 columns to map and some or all might be existing/missing
但我现在有 3 列要映射,部分或全部可能存在/缺失
Is there a good way to check if a column exist in a datatable?
有没有一种好方法可以检查数据表中是否存在列?
采纳答案by Aghilas Yakoub
You can use operator Contains
,
你可以使用operator Contains
,
private void ContainColumn(string columnName, DataTable table)
{
DataColumnCollection columns = table.Columns;
if (columns.Contains(columnName))
{
....
}
}
回答by asawyer
You can look at the Columns
property of a given DataTable
, it is a list of all columns in the table.
您可以查看Columns
给定的属性DataTable
,它是表中所有列的列表。
private void PrintValues(DataTable table)
{
foreach(DataRow row in table.Rows)
{
foreach(DataColumn column in table.Columns)
{
Console.WriteLine(row[column]);
}
}
}
http://msdn.microsoft.com/en-us/library/system.data.datatable.columns.aspx
http://msdn.microsoft.com/en-us/library/system.data.datatable.columns.aspx
回答by adinas
myDataTable.Columns.Contains("col_name")
回答by lokendra jayaswal
For Multiple columns you can use code similar to one given below.I was just going through this and found answer to check multiple columns in Datatable.
对于多列,您可以使用类似于下面给出的代码。我刚刚通过这个并找到了检查数据表中多列的答案。
private bool IsAllColumnExist(DataTable tableNameToCheck, List<string> columnsNames)
{
bool iscolumnExist = true;
try
{
if (null != tableNameToCheck && tableNameToCheck.Columns != null)
{
foreach (string columnName in columnsNames)
{
if (!tableNameToCheck.Columns.Contains(columnName))
{
iscolumnExist = false;
break;
}
}
}
else
{
iscolumnExist = false;
}
}
catch (Exception ex)
{
}
return iscolumnExist;
}
回答by Boopathi.Indotnet
DataColumnCollection col = datatable.Columns;
if (!columns.Contains("ColumnName1"))
{
//Column1 Not Exists
}
if (columns.Contains("ColumnName2"))
{
//Column2 Exists
}