关于C#使用foreach循环将对象添加到列表中

use*_*020 3 c#

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);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我有两个文件1.txt,并2.txtstring[]文件名.我将这些文件与db进行比较并获取值lstgAFPFileInfo.它第一次获得文件名1.txt并添加到列表中.第二次获得值2.txt但是在将文件添加到列表后,它会覆盖该值1.txt并再次添加2.txt.现在列表值是这样的list[0]:2.txt,list[1]: 2.txt 任何人都可以帮忙吗?

das*_*ght 7

这是因为您的循环不断地反复添加相同的对象,因此您的列表最终会对同一对象进行多次引用.

插图

添加projectfile = new ProjectFile()到循环的顶部以解决此问题.