how do I join two lists using linq or lambda expressions

C#

C# Problem Overview


I have two lists List<WorkOrder> and List<PlannedWork> I would like join the two lists on the workorder number as detailed below. In other words I have a list of planned work but I need to know the description of the work for the workOrderNumber.

I am new to both linq and lambda expressions, and I haven't quite got my head wrapped around them yet.

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# Solutions


Solution 1 - C#

The way to do this using the Extention Methods, instead of the linq query syntax would be like this:

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

Solution 2 - C#

It sounds like you want something like:

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

Solution 3 - C#

 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();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBradView Question on Stackoverflow
Solution 1 - C#NerdFuryView Answer on Stackoverflow
Solution 2 - C#Jon SkeetView Answer on Stackoverflow
Solution 3 - C#NaniView Answer on Stackoverflow