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

时间:2021-08-15 00:21:00

I've the following two classes;

我有以下两门课;

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; }
}

How can I extract the data into the format like

如何将数据提取到类似的格式中

(ModelId,Name,Enabled),(ModelId,Name,Enabled),(ModelId,Name,Enabled) etc

(ModelId名称,启用),(ModelId、名称、启用),(ModelId、名称、启用)等

2 个解决方案

#1


4  

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

That will give you string with False and True as Enabled values. If you want Enabled and Disabled instead, then use: m.Enabled ? "Enabled" : "Disabled" when formatting model string.

这将为您提供带有False和True作为启用值的字符串。如果您想要启用和禁用,那么使用:m。启用?“启用”:格式化模型字符串时“禁用”。


Full sample (with NBuilder used to create sample models):

完整的示例(使用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));

Output:

输出:

(1,Name1,False),(2,Name2,True),(3,Name3,False)

(1、Name1假),(2 Name2真实),(3 Name3假)

#2


0  

Try this:

试试这个:

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

#1


4  

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

That will give you string with False and True as Enabled values. If you want Enabled and Disabled instead, then use: m.Enabled ? "Enabled" : "Disabled" when formatting model string.

这将为您提供带有False和True作为启用值的字符串。如果您想要启用和禁用,那么使用:m。启用?“启用”:格式化模型字符串时“禁用”。


Full sample (with NBuilder used to create sample models):

完整的示例(使用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));

Output:

输出:

(1,Name1,False),(2,Name2,True),(3,Name3,False)

(1、Name1假),(2 Name2真实),(3 Name3假)

#2


0  

Try this:

试试这个:

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