簡體   English   中英

C# Linq 語法加入

[英]C# Linq Syntax Join

我有一個List<Customer> ,它具有另一個子List<CustomerOrder>的屬性。 然后我有一個客戶訂單和錯誤List<OrderError> 我怎樣才能最好地使用錯誤消息更新子列表。 這是它的樣子:

Customer Class:
CustomerId
CustomerName
CustomerLocation
List<CustomerOrder> Orders

CustomerOrder Class:
OrderId
OrderStatus
ErrorMessage

OrderError Class:
OrderId
ErrorMessage

我需要做的是更新 CustomerOrder 類 OrderStatus,如果我沒有錯誤,它將被設置為“P”,如果我在 List 中有錯誤我想將 OrderStatus 更新為“F”,然后是 ErrorMessage . 我想知道是否不是用 join 做一個“新”列表,我相信 DefaultEmpty 如果有更好的方法來做到這一點。

代碼:

var customers = new List<Customer>();
Customer cust1 = new Customer();
cust1.CustomerId = 1;
cust1.CustomerName = "ABC Corp";
cust1.CustomerLocation = "Raliegh";

var customerOrders = new List<CustomerOrder>();
CustomerOrder custOrd1 = new CustomerOrder();
custOrd1.OrderId = "152654";
customerOrders.Add(custOrd1);

CustomerOrder custOrd2 = new CustomerOrder();
custOrd2.OrderId = "155000";
customerOrders.Add(custOrd2);

cust1.Orders = customerOrders;
customers.Add(cust1);

Customer cust2 = new Customer();
cust2.CustomerId = 2;
cust2.CustomerName = "DEF Corp";
cust2.CustomerLocation = "Tilo";

customerOrders = new List<CustomerOrder>();
custOrd1 = new CustomerOrder();
custOrd1.OrderId = "200012";
customerOrders.Add(custOrd1);

cust2.Orders = customerOrders;
customers.Add(cust2);

然后是 OrderErrors 列表:

var orderErrors = new List<OrderError>();
OrderError err = new OrderError();
err.OrderId = "155000";
err.ErrorMessage = "Order Failed Validation";

orderErrors.Add(err);

我需要在 orderErrors 像客戶列表中的 OrderId 上方一樣填充之后進行更新。

我會用字典:

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            List<CustomerOrder> orders = new List<CustomerOrder>();
            List<OrderError> orderErrors = new List<OrderError>();

            Dictionary<string, OrderError> dictOrderErrors = orderErrors
                .GroupBy(x => x.OrderId, y => y)
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());

            foreach (CustomerOrder order in orders)
            {
                order.ErrorMessage = dictOrderErrors[order.OrderId].ErrorMessage;
            }

        }
    }
    public class CustomerOrder
    {
        public string OrderId { get; set; }
        public string OrderStatus { get; set; }
        public string ErrorMessage { get; set; }
    }
    public class OrderError
    {
        public string OrderId { get; set; }
        public string ErrorMessage { get; set; }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM