C# Linq 连接问题

标签 c# linq

我正在尝试连接两个对象列表,并将第一个对象(ProductReport)中的属性(收入)更新为与连接对象(交易)中的属性(收入)相同。代码如下:

using System.Collections.Generic;
using System.Linq;

namespace TestConsole
{
    public class ProductReport
    {
        public string productName { get; set; }
        public int PrdouctID { get; set; }
        public double Revenue { get; set; }
    }

    public class Transaction
    {
        public double Revenue { get; set; }
        public int PrdouctID { get; set; }
    }

    public class Program
    {
        static void Main(string[] args)
        {
            List<ProductReport> products = new List<ProductReport>();
            ProductReport p = new ProductReport();
            p.productName = "Sport Shoe";
            p.PrdouctID = 1;

            products.Add(p);

            List<Transaction> transactions = new List<Transaction>();
            Transaction t1 = new Transaction();
            t1.PrdouctID = 1;
            t1.Revenue = 100.0;

            Transaction t2 = new Transaction();
            t2.PrdouctID = 1;
            t2.Revenue = 200.00;

            transactions.Add(t1);
            transactions.Add(t2);

            var results = (from product in products
                           join transaction in transactions on product.PrdouctID equals transaction.PrdouctID into temp
                           from tran in temp.DefaultIfEmpty()
                           select new { product, tran }
                           ).ToList();

            results.ForEach(x => x.product.Revenue = x.tran.Revenue);
        }

    }
}

该代码根据 ProductID 连接 2 个对象列表。我期望在结果对象中看到两个 ProductReport 项目,收入分别为 100.00 和 200.00。但是,foreach 函数会以某种方式覆盖第一个 ProductReport 中的收入属性。最终,两个 ProductReport 的收入都是 200.00。谁能帮我解决这个问题以及如何轻松获得我想要的结果 ?谢谢。

最佳答案

您只需要更改您的加入

var results = (from p in products
join t in transactions on p.ProductID equals t.ProductId
select new ProductReport{
  ProductName = p.productName,
  ProductId = p.ProductID,
  Revenue = t.Revenue
}).ToList();

然后您将获得一个列表,其中包含 2 个 ProductId = 1(运动鞋)的条目

ProductName = "Sport Shoe"
ProductId = 1
Revenue = 200.00

ProductName = "Sport Shoe"
ProductId = 1
Revenue = 100.00

关于C# Linq 连接问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49911399/

相关文章:

javascript - 在 ASP.Net MVC 5 中将 javascript 数组从 View 传递到 Controller

c# - Ajax webmethod 仅在第一次尝试时无法触发存储过程

c# - 如何使二进制乘法运算符 * 在泛型类中可用?

c# - 选项卡上的监听器单击或激活无法正常工作/extjs4

c# - 如何从人员列表中查询孙辈?

c# - LINQ to Entities 无法识别方法 'System.DateTime ConvertTimeFromUtc(System.DateTime, System.TimeZoneInfo)' 方法

c# - 如何从 [C# WP8.1 WRT/SL] 项目中调用 [Unmanaged C++ DLL func]

c# - 已解析上下文 (.toList()) 和未解析上下文的区别

c# - 树遍历 API 的访问者模式与 LINQ 风格的流畅语法

c# - 使用 LINQ 基于多个参数进行过滤?