.Net List ForEach Item
.net, c#, foreach, linq, list
Solution
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:
foreach(ClassA item in List1)
{
item.myObjectB = List2.FirstOrDefault(b => b.Id == item.Id);
}
This will set the item every time, though it will be set to `null` if there is no match. If you already have items in `myObjectB` and setting them to null is inappropriate, you could use:
foreach(ClassA item in List1)
{
item.myObjectB = List2.FirstOrDefault(b => b.Id == item.Id) ?? item.myObjectB;
}
Problem
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!!!