CoolDiva
CoolDiva

Reputation: 209

Difference between numbers present in two different lists based on another property using LINQ

I have 2 different lists of an entity GraphData

class GraphData
{
DateTime date{get; set;}
double price{get;set;}
}

Now I have 2 different lists like List list1 and List list2

For example

list1 has followin values

1/1/2011,20.99
1/1/2012,45.67
31/03/2012,67.44

list2 has following values

1/1/2011,22.99
1/1/2012,90.67
31/03/2012,66.44
8/08/2013,70.77

Now I want to have a difference list List diffData

which calculates the difference between above 2 lists(list1,list2) only if the date is same

Result should be

1/1/2011,02.00(22.99-20.99)
1/1/2012,45.00(90.67-45.67)
31/03/2012,-1.00(66.44-67.44)

How can I do this using LINQ?

Upvotes: 0

Views: 100

Answers (2)

Dmytro Rudenko
Dmytro Rudenko

Reputation: 2524

list1.Join(list2, x => x.date, x => x.date, (x, y) => new GraphData {date = x.date, price = y.price - x.price});

Upvotes: 2

Magnus
Magnus

Reputation: 46929

This should do it:

var q = from a in l1
    join b in l2 on a.date equals b.date
    select new GraphData()
    {
        date = a.date,
        price = b.price - a.price
    };

And if you always want a positive difference you can write price = Math.Abs(a.price - b.price)

Upvotes: 2

Related Questions