C #: How do I iterate over content in a DataColumn?

I have a database column. I just need to check if the value is there.

        DataTable dt = masterDataSet.Tables["Settings"];
        DataColumn SETTINGS = dt.Columns["DEFAULTSETTINGS"];

      

I just need to iterate over the values ​​in that column to see if the value exists. Help

+2


source to share


3 answers


You are iterating over rows, not columns



DataColumn SETTINGS = dt.Columns["DEFAULTSETTINGS"];
foreach(DataRow row in dt.Select())
{
    object columnValue = row[SETTINGS];
    // Do something with columnValue
}

      

+4


source


There is no need to use Linq or manually iterate through DataRows as plain old ADO.NET has several solutions like DataTable.Select and DataView.RowFilter .


string value = "default"; 
bool found = dt.Select("DEFAULTSETTINGS = " + value).Length > 0;

      



Obviously, once you get the filtered rows, you can do whatever you want with them. In my example, I just checked to see if any string was within the criteria, but you can manipulate them as you see fit.

+3


source


You can use linq in .net 3.5:


DataColumn col = dt.Columns["DEFAULTSETTINGS"];
object value = //expected value
bool valueExists = dt.AsEnumerable().Any(row => row.Field<object>(col).Equals(value));

      

EDIT: It seems from the comments you are trying to see if the "DEFAULTSETTINGS" column contains the string "default". The field extension method simply passes the object in datarow on that column to the given type, so you can change the type parameter rather than using ToString (). So for your example, you can probably use this:


DataColumn col = dt.Columns["DEFAULTSETTINGS"];
bool valueExists = dt.AsEnumerable().Any(row => "default".Equals(row.Field<string>(col), StringComparison.OrdinalIgnoreCase);

      

+1


source







All Articles