gpt4 book ai didi

c# - 将类属性转换为键值对

转载 作者:太空狗 更新时间:2023-10-29 22:23:23 26 4
gpt4 key购买 nike

我有这两个类

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 应该是键,值应该是 KeyValue 类的值,如果我通过 SellerReportClass,那么 Entityname 应该是键,EntityAmt 应该是值

想知道怎么做

注意:我将获得两个类(class)的列表

最佳答案

您可以在 C# 中使用 implicit 运算符将其转换为您想要的 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));

关于c# - 将类属性转换为键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13026484/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com