简体   繁体   English

使用Linq减去两个数组

[英]Subtracting two arrays using Linq

I've two arrays arr1 and arr2 of the following type 我有以下类型的两个数组arr1arr2

class Data
{
  public int IdProduct;
  public double Price;
}

and I need to subtract the Price of arr2 to arr1 but the items of the arrays are the result of different queries so the amount of products in arr1 not necessarily match the amount of products in arr2 and there're no duplicated products in the arrays. 并且我需要将arr2的价格减去arr1,但数组的项目是不同查询的结果,因此arr1中的产品数量不一定与arr2中的产品数量匹配,并且数组中没有重复的产品。

I need to do the subtraction product by product in each array, ie. 我需要在每个数组中逐乘积相减。

var total =
  from a1 in arr1
  join a2 in arr2 on a1.IdProducto equals a2.IdProducto
  select new
  {
    Product = a1.IdProduct,
    Price = a1.Price - a2.Price
  };

Something like this? 像这样吗

var q = from a in arr1
                  join b in arr2 on a.IdProduct equals b.IdProduct into c
              from x in c.DefaultIfEmpty()
              select new Data {
                IdProduct = a.IdProduct,
                Price = x == null ? a.Price : a.Price - x.Price
              };

arr1 = q.ToArray();
var result = arr1.Concat(arr2)
            .GroupBy(d => d.IdProduct)
            .Select(x => new Data
            {
                IdProduct = x.Key,
                Price = x.Select((y,i) => i == 0 ? y.Price : -y.Price).Sum()
            }).ToList();

You have two arrays of Data with a total price difference ? 您有两个总价差Data数组?

arr1.Sum(d => d.Price) - arr2.Sum(d => d.Price);

Basically this code sums up both arrays and subtracts afterwards. 基本上,此代码对两个数组求和,然后相减。 The total effort is therefore linearly growing with the length of the arrays: O(n+m) . 因此,总工作量随着数组的长度呈线性增长O(n+m)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM