regarding C# adding objects to list using foreach loop
c#
Solution
This is because your loop keeps adding the same object over and over, so your list ends up with multiple references to the same object.
Add `projectfile = new ProjectFile()` to the top of your loop to fix this problem.
Problem
``` foreach (string f in fileName) { if (list.Where(p => p.FileName.Trim().Equals(f.Trim(), StringComparison.OrdinalIgnoreCase)).Count() == 0) { ServerpathID = GetSourceServerPath(projectID, out ServerPath); DellDirectory dir = new DellDirectory(ServerPath); lstgAFPFileInfo = GetFilesFromSourceServer(new string[] { f }, ServerpathID, SearchOption.TopDirectoryOnly).ToList(); if (lstgAFPFileInfo.Count() != 0) { foreach (Service.GAFPFileInfo lstg in lstgAFPFileInfo) { projectfile.Checksum = string.Empty; projectfile.IsAutoDeleted = (autoDelete == true) ? true : false; projectfile.Size = lstgAFPFileInfo[0].Size; projectfile.IsArchived = false; projectfile.ProjectFileId = 0; projectfile.Language.LanguageId = 1; projectfile.LastModifyDate = lstgAFPFileInfo[0].LastModified; projectfile.ProjectPartLink = projectPartLink; projectfile.FileName = f; list.Add(projectfile); } } } } ``` I have two files `1.txt` and `2.txt` in `string[]` filename. I am comparing these files with db and getting values into `lstgAFPFileInfo`. The first time it got the filename `1.txt` and added to list. 2nd time it got the value `2.txt` but after adding the file to the list it is overwrite the value `1.txt` and again it added `2.txt`. Now the list values are like this `list[0]:2.txt` and `list[1]: 2.txt` Can anyone help on this?