1

How I convert boolean value to int (1 for True and 2 for false) inside ItemArray. Below is function for converting DataTable to csv.

public  string ToCSV(DataTable tbl, Boolean ColumnHeader)
    {
        string FinalResult = string.Empty;
        StringBuilder strb = new StringBuilder();

        if (ColumnHeader == true)
        {
            //column headers
            strb.AppendLine(string.Join(",", tbl.Columns.Cast<DataColumn>()
                .Select(s => "\"" + s.ColumnName + "\"")));
        }
        //rows
        tbl.AsEnumerable().Select(s => strb.AppendLine(
           string.Join(",", s.ItemArray.Select(
               i => "\"" + i.ToString() + "\"")))).ToList();
        FinalResult = strb.ToString();
        strb= null;
        return FinalResult; 
        //return strb.ToString();
    }
5
  • You could write an extendion method for bool called e.g. ToInt() and retruning an int Commented Aug 17, 2016 at 13:32
  • The boolean column containing True /false value in datatable. Commented Aug 17, 2016 at 13:34
  • Use BitConverter.ToBoolean Commented Aug 17, 2016 at 13:38
  • The strb= null; line is a holdover from how things used to work in the vb6/vbscript era. It's no longer useful or helpful, and in rare cases can actually be harmful to your code. Commented Aug 17, 2016 at 13:58
  • @MusakkhirSayyed Are you going to accept the answer i gave? if not exlpain why my answer does not solve the problem so we can think of a different solution for you Commented Aug 18, 2016 at 6:38

1 Answer 1

2
List<bool> data = new List<bool>() { true, false, false, true };
List<int> intdata = data.Select(x => x ? 1 : 2).ToList();

if you are receiving the true or false as string you can simple change the if statement
from x ? 1: 2 to x == "true" ? 1 : 2

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.