-2

Hai My problem is I have 2 list of generic objects

 List<plan> previousYear;  
 List<plan> Nextyear;  

and I need to get the difference between them in a custom way

for eg:

public class plan{
         int budget;
         int expense;
         int savings 
}

   List<plan> previousYear = new List<plan>() { new plan ( 100, 200, 300 ), 
                            new plan( 400, 500, 600 ) };  

   List<plan> nextYear = new List<plan>() { new plan ( 200, 200, 300 ), 
                         new plan ( 400, 600, 700 ) };  

After applying difference I Need to get result like

  1. First object First property changed to 200

  2. Second object second property changed to 600

  3. Second object third pr0perty changed to 700

I would like to get the above result in a list.
I don't know the data structures and methods(like linq) to be used for solving this problem

Aristos
  • 66,005
  • 16
  • 114
  • 150
Robert_Junior
  • 1,122
  • 1
  • 18
  • 40

2 Answers2

2

You can use Zip method:

var result = previousYear.Zip(nextYear,
            (p, n) =>
                new plan(Math.Max(p.budget, n.budget), 
                    Math.Max(p.expense, n.expense),
                    Math.Max(p.savings, n.savings)))
                    .ToList();
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
1

At first you could overload the - operator for your custom class called Plan, like below:

public class Plan
{
    public int Budget { get; set; }
    public int Expense{ get; set; }
    public int Savings { get; set; }

    public Plan(int budget, int expense, int savings)
    {
        Budget = budget;
        Expense = expense;
        Savings = savings;
    }

    public static Plan operator -(Plan p1, Plan p2)
    {
        return new Plan(p1.Budget - p2.Budget, 
                        p1.Expense - p2.Expense, 
                        p1.Savings - p2.Savings);
    }
}

Then you could use the Zip method of LINQ to get what you want, like below:

var result = previousYear.Zip(nextYear, (p,n) => p-n);

For more information about Zip method, please have a look here.

Christos
  • 53,228
  • 8
  • 76
  • 108