使用C#

时间:2019-03-01 23:09:37

标签: c# .net c#-4.0

我有一个如下所示的班级:

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中。

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

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

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

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();

答案 2 :(得分:0)

如果只想在两行中执行此操作,然后将第一个列表序列化为JSON,然后将其反序列化为第二个类的列表,则它将起作用。