Your first block of code creates a new instance inside the loop, and then immediately checks to see if this exact instance is already in the collection. This cannot be - you just created it.
You could write like this:
List<CustomerSummary> summaries = new List<CustomerSummary>(); for (var i = 0; i < 10; i++) { var summary = new CustomerSummary { ID = 1, Name = "foo", balance = 50.00 }; summaries.Add(summary); }
The second block of code checks for the presence of any element in the collection with the corresponding identifier. Since you have hardcoded identifier 1, you are only going to add the element for the first time. Each instance created after that will return false in the if and will not be added.
You can change this behavior by changing the identifier:
for (var i = 0; i < 10; i++) { var summary = new CustomerSummary { ID = i, Name = "foo", balance = 50.00 }; if (!summaries.Any(s=> s.ID == summary.ID)) summaries.Add(summary); }
Again, the if no longer needed, since you know that the identifier can no longer exist in the collection, so you can simply remove the check.
source share