I have 2 objects:
public class ClassA
{
public int Id
public string name;
public ClassB myObjectB;
}
public class ClassB
{
public int Id
public string name
}
Having 2 Lists for <ClassA> <ClassB>
Some items from List1 match by Id with an item on List2… I want to set the objectB foreach item…
foreach(ClassA item in List1)
{
ClassB obj = (from b in List2 where b.Id == item.Id select b).SingleOrDefault()
if(obj != null)
{
item.myObjectB = obj;
////////break; <- ignore this
}
}
This solution works for me, but I’m just wondering if there is a better way to do this, instead of Foreach
Thanks everyone for your help!!!
I think that a
foreach, in this case, is actually the appropriate approach, as you’re mutating your list. You could potentially simplify your code a bit, however:This will set the item every time, though it will be set to
nullif there is no match. If you already have items inmyObjectBand setting them to null is inappropriate, you could use: