如何使用datatable在itemarray中将boolean转换为int?

时间:2016-08-17 13:31:10

标签: c# datatable

如何在boolean内将True值转换为int(false为1,ItemArray为2)。以下是将DataTable转换为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();
    }

1 个答案:

答案 0 :(得分:2)

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

如果您收到true或false字符串,则可以简单地将if语句从x ? 1: 2更改为x == "true" ? 1 : 2