No it is not strange because you declare and initialize the object membHier
just one time before the loop and then try to insert in the new list the same object.
This will resolve your problem
List<Classes.MemberHierarchy> membHierList = new List<Classes.MemberHierarchy>();
foreach (KeyValuePair<string, string[]> acct in acctData)
{
Classes.MemberHierarchy membHier = new Classes.MemberHierarchy();
membHier.entityName = acct.Key;
membHier.Accounts = acct.Value;
membHierList.Add(membHier);
}
Declaring a NEW instance of the object MemberHierarchy
at every loop will populate the list with different instances and every instance has its own values.
Instead, with the initialization outside the loop, at every iteration you update the same instance with the extracted values. But membHier
is a reference type, so if not reinitialized, it points at the same memory where are stored the values of the first entity and you effectively overwrite these values with the second entity. At the end, all the elements in the list points to the same memory location and these memory locations contains the data of the last entity