[英]Difference between numbers present in two different lists based on another property using LINQ
I have 2 different lists of an entity GraphData 我有2个不同的实体GraphData列表
class GraphData
{
DateTime date{get; set;}
double price{get;set;}
}
Now I have 2 different lists like List list1 and List list2 现在我有2个不同的列表,如列表list1和List list2
For example 例如
list1 has followin values list1具有followin值
1/1/2011,20.99
1/1/2012,45.67
31/03/2012,67.44
list2 has following values list2具有以下值
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 现在我想要一个差异列表List diffData
which calculates the difference between above 2 lists(list1,list2) only if the date is same 仅当日期相同时才计算上述两个列表(list1,list2)之间的差异
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? 如何使用LINQ做到这一点?
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)
而且,如果您始终希望获得正的差额,则可以写出
price = Math.Abs(a.price - b.price)
list1.Join(list2, x => x.date, x => x.date, (x, y) => new GraphData {date = x.date, price = y.price - x.price});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.