我有一个如下所示的课程:
公共类BidCostModel { 公共字符串代码{get;组; } 公共小数?第1个月{得到;组; } 公共小数?第2个月{得到;组; } 公共小数? …
不需要依赖一些外部工具。即使使用工具,您也需要定义“格式化”类并配置工具以格式化某些属性。
创建一个负责“格式化”值的类
public class BidCostFormatted { private readonly BidCostModel _model; public string Code => _model.Code; public string Month1 => _model.Month1.ForView(); public string Month2 => _model.Month2.ForView(); public string Month3 => _model.Month3.ForView(); public BidCostFormatted(BidCostModel model) => _model = model; } public static class Extensions { public static string ForView(this decimal? value) { if (value.HasValue) { return value.Value.ToString("N"); } return string.Empty; } }
然后格式化将是容易和可维护的
var formattedBidCosts = bidCosts.Select(cost => new BidCostFormatted(cost)).ToList();
如果你想只用两行,那么将第一个列表序列化为JSON,然后将它想到第二个类的列表,它就可以了。
也许格式化原始值 ToString("N") 并将其附加到新列表:
ToString("N")
list2.AddRange( list1.Select( a => { b = new BidCostModelFormatted(); b.Code = a.Code; b.Month1 = a.Month1.ToString("N"); b.Month2 = a.Month2.ToString("N"); b.Month3 = a.Month3.ToString("N"); return b; } ) );