【问题标题】:Merging two objects or more and display their sum合并两个或更多对象并显示它们的总和
【发布时间】:2023-04-04 17:26:01
【问题描述】:

我想合并这两个对象并在新对象中显示它们的总和

我要实现的第一个目标是我有两个目标销售额为 100 的对象,然后结果必须为 200。

我要实现的第二个目标是两个对象具有数组并且数组包含不同的值。 如果两个对象被合并,则新对象中数组的值就是这两个对象的值

我的班级的简单例子

public class IncentivePayout
    {
        public decimal Sales { get; set; }

        public List<IncentivePayoutDetail> IncentivePayoutDetails { get; set; }
    }

public class IncentivePayoutDetail
    {
        public string ProductFamilyName { get; set; }

    }

例子

 totalEthical: {
            target: 100,
            incentivePayoutDetails: [
                {

                    productFamilyName: X,
                },
                ]

 totalConsumer: {
            target: 100,
            incentivePayoutDetails: [
                {

                    productFamilyName: Y,
                },
                ]




我想要达到的结果是

 newObject: {
            target: 200,
            incentivePayoutDetails: [
                {

                    productFamilyName: X,
                },
                {

                    productFamilyName: Y,
                },
                ]



【问题讨论】:

  • 这是json还是类?
  • 欢迎来到 SO。能否请您展示一下您到目前为止所做的尝试。
  • 这是 c# 对象
  • 你会在这个问题上添加你的课程吗?
  • 是的。我有课。当然。这是成为 api 的 c# 对象

标签: c#


【解决方案1】:

好的,这是我的解决方案。很简单。 Link to codeshare. 我假设你的课程可能是什么样子。如果有任何不一致,请尝试根据您的需要进行修改。

如果代码共享不起作用。 :

class Ethical{
    public int SomeValue = {get;private set;}
    public List<PayoutDetails> details = {get; private set;}

    public Ethical(int SomeValue){
    this.SomeValue = SomeValue;
    this.details = new List<PayoutDetails>();
  }

  public Ethical(){
    this.SomeValue = 0;
    this.details = new List<PayoutDetails>();
  }

  public void AddPayoutDetails(PayoutDetails details){
    this.details.add(details);
  }

  public void AddPayoutDetails(List<PayoutDetails> details){
    details.ForEach(el => this.details.Add(el));
  }

  public void AddToValue(int anyNumber){
    SomeValue += anyNumber;
  }

}


//for merging 2 objects
public static Ethical sumEthicalProperties(Ethical obj1, Ethical obj2){
    Ethical newObj = new Ethical(obj1.SomeValue + obj2.SomeValue)
  newObj.Add(obj1.details);
  newObj.Add(obj2.details);
  return newObj;
}

//MoreUniversal
public static Ethical sumEthicalProperties(params Ethical[] objs){

  int fullSum = 0;
  Ethical newObj = new Ethical()
  foreach(Ethical singleObj in objs){
    fullSum += singleObj.SomeValue;
    newObj.AddPayoutDetails = singleObj.details;
  }
  newObj.AddToValue(fullSum;
  return newObj;
}

【讨论】:

  • 感谢您提供答案,请将 C# 代码添加到您的问题中,因为链接可能会随着时间的推移而断开。
  • 感谢 Oleg Musjenko 的想法。我的问题现在解决了
猜你喜欢
  • 1970-01-01
  • 2015-01-06
  • 2010-10-22
  • 2017-11-22
  • 2015-12-21
  • 2018-09-02
  • 1970-01-01
  • 2021-04-16
  • 2022-10-04
相关资源
最近更新 更多