none
How to replace boolean values in DataTable using linq query or simple foreach loop RRS feed

  • Question

  • Hi,

    I have a DataTable with few columns and a couple of boolean columns with values as true and false. I want to replace boolean columns values from true and false to 1 and 0 respectively by using simple c# code.

    It would be good if you can do this by using LINQ query otherwise, just use simple foreach loop.

    Any ideas ?

    Thanks,

    Prav

    Tuesday, February 2, 2016 3:59 PM

Answers

  •    //1# Using linq is straight forward ..
                DataTable dt = new DataTable();
                dt.Columns.Add("ID", typeof(int));
                dt.Columns.Add("Flag1", typeof(bool));
                dt.Columns.Add("Flag2", typeof(bool));
                dt.Rows.Add(25, true, false);
                dt.Rows.Add(50, false, false);
                dt.Rows.Add(50, true, true);
                var query = from p in dt.AsEnumerable()                        
                            select new
                            {
                                ID = p.Field<int>("ID"),
                                Flag1 =p.Field<bool>("Flag1") ? 1 : 0,
                                Flag2 =p.Field<bool>("Flag2") ? 1 : 0
                            };
    
                foreach (var el in query)
                {
                    Console.WriteLine(" {0} {1} {2} ", el.ID, el.Flag1, el.Flag2);
                }
    
                //2# Create a new integer column for every bool column in your datatable and use for loop to copy bool to int and remove the bool columns.. ?
                //couple of for loops ..
                //3# read/manipulate xml files .. ?

    • Marked as answer by praveench2k Friday, February 5, 2016 1:24 PM
    Tuesday, February 2, 2016 5:49 PM