5

我有这两个课

public class BuyEstimateResult
{
    public string SubTitle { get; set; }
    public string Value { get; set; }
    public string Formulae { get; set; }
}
public class SellerReportClass
{
    public string Entityname { get; set; }
    public double EntityAmt { get; set; }
    public string Formulae { get; set; }
}

我必须使它们应该转换为

public class KeyValue
{
    public string key {get;set;}
    public string value {get;set;}
}

如果我通过 BuyEstimateResult,它的 SubTitle 应该是 key,Value 应该是 KeyValue 类的 Value,如果我通过 SellerReportClass,那么 Entityname 应该是 key,EntityAmt 应该是 Value

任何想法怎么做

注意:我会得到这两个类的列表

4

1 回答 1

10

您可以使用implicitC# 中的运算符将其转换为KeyValue您想要的 - http://msdn.microsoft.com/en-us/library/z5z9kes2(v=vs.110).aspx

public static implicit operator KeyValue(BuyEstimateResult ber)
{
     return new KeyValue { Key = ber.SubTitle, Value = ber.Value }
}

编辑

要更具体地了解如何实现这一点:

public class BuyEstimateResult
{
    public string SubTitle { get; set; }
    public string Value { get; set; }
    public string Formulae { get; set; }

    public static implicit operator KeyValue(BuyEstimateResult ber)
    {
        return new KeyValue {Key = ber.SubTitle, Value = ber.Value};
    }
}

public class SellerReportClass
{
    public string Entityname { get; set; }
    public double EntityAmt { get; set; }
    public string Formulae { get; set; }

    public static implicit operator KeyValue(SellerReportClass sell)
    {
        return new KeyValue { Key = sell.Entityname, Value = sell.EntityAmt.ToString(CultureInfo.InvariantCulture)};
    }
}

public class KeyValue
{
    public string Key { get; set; }
    public string Value { get; set; }
}

public class Program
{
    static void Main()
    {
        var listB = new List<BuyEstimateResult>
                        {
                            new BuyEstimateResult {SubTitle = "BER1", Value = "BER1_VALUE"},
                            new BuyEstimateResult {SubTitle = "BER2", Value = "BER2_VALUE"}
                        };

        var listS = new List<SellerReportClass>
                        {
                            new SellerReportClass {Entityname = "SELL1", EntityAmt = 1.0},
                            new SellerReportClass {Entityname = "SELL2", EntityAmt = 2.5}
                        };

        foreach (KeyValue kv in listB)
            Console.WriteLine(kv.Key + ":" + kv.Value);

        foreach (KeyValue kv in listS)
            Console.WriteLine(kv.Key + ":" + kv.Value);
    }
}

要从两个不同的列表中获取一个KeyValue对象列表,您可以执行以下操作:

var KeyValueList = listB.ConvertAll(i => (KeyValue) i);
KeyValueList.AddRange(listS.ConvertAll(i => (KeyValue) i));
于 2012-10-23T08:41:40.523 回答