我有以下两个类;
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)等
答案 0 :(得分:4)
String.Join(",", models.Select(m => String.Format("({0},{1},{2})", m.ModelId, m.Name, m.Enabled)));
这将为您提供False
和True
字符串作为启用值。如果您想要Enabled
和Disabled
,请在格式化模型字符串时使用: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);