如何使用 linq 或 lambda 表达式连接两个列表

问题描述 投票:0回答:3

我有两个列表

List<WorkOrder>
List<PlannedWork>
我想将这两个列表加入到工单编号上,详情如下。换句话说,我有一个计划工作列表,但我需要知道 workOrderNumber 的工作描述。

我对 linq 和 lambda 表达式都很陌生,而且我还没有完全理解它们。

class WorkOrder
{
    public int WorkOrderNumber { get; set; }
    public string WorkDescription { get; set; }
}

class PlannedWork
{
    public int WorkOrderNumber { get; set; }
    public DateTime ScheduledDate { get; set; }
}
c#
3个回答
126
投票

使用扩展方法而不是 linq 查询语法来执行此操作的方法如下:

var results = workOrders.Join(plans,
  wo => wo.WorkOrderNumber,
  p => p.WorkOrderNumber,
  (order,plan) => new {order.WorkOrderNumber, order.WorkDescription, plan.ScheduledDate}
);

113
投票

听起来你想要类似的东西:

var query = (from order in workOrders
            join plan in plans
                 on order.WorkOrderNumber equals plan.WorkOrderNumber
            select new
            {
                order.WorkOrderNumber,
                order.Description,
                plan.ScheduledDate
            }).ToList();

8
投票
 public class State
        {
            public int SID { get; set; }
            public string SName { get; set; }
            public string SCode { get; set; }
            public string SAbbrevation { get; set; }
        }

        public class Country
        {
            public int CID { get; set; }
            public string CName { get; set; }
            public string CAbbrevation { get; set; }
        }


 List<State> states = new List<State>()
            {
               new  State{  SID=1,SName="Telangana",SCode="+91",SAbbrevation="TG"},
               new  State{  SID=2,SName="Texas",SCode="512",SAbbrevation="TS"},
            };

            List<Country> coutries = new List<Country>()
            {
               new Country{CID=1,CName="India",CAbbrevation="IND"},
               new Country{CID=2,CName="US of America",CAbbrevation="USA"},
            };

            var res = coutries.Join(states, a => a.CID, b => b.SID, (a, b) => new {a.CName,b.SName}).ToList();
© www.soinside.com 2019 - 2024. All rights reserved.