Home > other >  How to change the following foreach code to Linq Query?
How to change the following foreach code to Linq Query?

Time:09-23

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

CodePudding user response:

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;

CodePudding user response:

You can join two lists and then enumerate:

var items = TopAClassData.data
    .Join(TopBClassData.Data, x => x.ID, x => x.NewId, 
       (item, anotherItem) => item);

foreach(var item in items)
{
    item.values = anotherItemD.Differentvalues;
}
  • Related