繁体   English   中英

将数据从一个列表复制到另一个列表,同时使用C#对其进行格式化

[英]Copy data from one list to another while formatting it in C#

我有一个如下所示的课程:

public class BidCostModel {
    public string Code { get; set; }
    public decimal? Month1 { get; set; }
    public decimal? Month2 { get; set; }
    public decimal? Month3 { get; set; }       
}

我创建了一个列表,并使用EF将其填充了一些数据:

List<BidCostModel> list1 = new List<BidCostModel>();
fillOperation(data);

我有另一个具有相似属性名称但数据类型不同的类

public class BidCostModelFormatted {
    public string Code { get; set; }
    public string Month1 { get; set; }
    public string Month2 { get; set; }
    public string Month3 { get; set; }        
}

List<BidCostModelFormatted> list2 = new List<BidCostModelFormatted>();

我想在添加千个分隔符的同时将数据从list1复制到list2 是否有一个映射工具或一些我可以使用的工具,而无需执行foreach循环来将数据复制到list2时添加数千个分隔符。

也许使用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;
        }
    )
);

无需依赖某些外部工具。 即使使用工具,您也需要定义“格式化的”类并配置工具以格式化某些属性。

创建一个负责“格式化”值的类

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,然后将其反序列化为第二个类的列表,则它将起作用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM