Search code examples
c#linq.net-core

How to change the following foreach code to Linq Query?


public class A
{
    public List<Data> data { get; set; }
}

public class Data
{
    public int ID { get; set; }
    public int values { get; set; }
}

public class B
{
    public List<DifferentData> Data { get; set; }
}

public class DifferentData
{
    public int NewID { get; set; }
    public int Differentvalues { get; set; }
    public string AdditionalInfo { get; set; }
}

I have a code like below

var TopAClassData = new A();
var TopBClassData = new B();
var anotherItemD = new DifferentData();

foreach (var item in TopAClassData.data)
{
    foreach (var anotherItem in TopBClassData.Data)
    {
        if (item.ID == anotherItem.NewID)
        {
            item.values = anotherItemD.Differentvalues;
        }
    }
}

I'm trying to set the Differentvalues from the List to values field of List if the NewId and ID are matching. Is there anyway to convert the foreach code to simpler linq query


Solution

  • Here's a fairly nice LINQ version:

    IEnumerable<Data> items =
        from item in TopAClassData.data
        join anotherItem in TopBClassData.Data on item.ID equals anotherItem.NewID
        select item;
        
    foreach (Data item in items)
        item.values = anotherItemD.Differentvalues;