将列表转换为逗号分隔的MySQL插入语句

时间:2013-08-05 13:42:18

标签: c# mysql csv

我有以下两个类;

public class CarModels
{
    public List<Model> Model{ get; set; }

    public CarModels()
    {
        Model = new List<Model>();
    }
}

public class Model
{
    public int ModelId { get; set; }
    public string Name { get; set; }
    public bool Enabled{ get; set; }
}

如何将数据提取为

之类的格式

(ModelId,Name,Enabled),(ModelId,Name,Enabled),(ModelId,Name,Enabled)等

2 个答案:

答案 0 :(得分:4)

String.Join(",", models.Select(m => String.Format("({0},{1},{2})", m.ModelId, m.Name, m.Enabled)));

这将为您提供FalseTrue字符串作为启用值。如果您想要EnabledDisabled,请在格式化模型字符串时使用:m.Enabled ? "Enabled" : "Disabled"


完整样本(使用NBuilder创建样本模型):

IEnumerable<Model> models = Builder<Model>.CreateListOfSize(3).Build();
Func<Model, string> formatModel = 
    m => String.Format("({0},{1},{2})", m.ModelId, m.Name, m.Enabled);
string result = String.Join(",", models.Select(formatModel));

输出:

  

(1,NAME1假),(2,NAME2真),(3,NAME3,FALSE)

答案 1 :(得分:0)

试试这个:

var models = carModels.Model.Aggregate<Model, string>("", (s, m) =>
{
    return s + String.Format(",({0},{1},{2})", m.ModelId, m.Name, m.Enabled);
}).Substring(1);