关于C#使用foreach循环将对象添加到列表 [英] regarding C# adding objects to list using foreach loop

查看:48
本文介绍了关于C#使用foreach循环将对象添加到列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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);
            }
        }
    }
}

我在 string [] 文件名中有两个文件 1.txt 2.txt .我正在将这些文件与db进行比较,并将值添加到 lstgAFPFileInfo 中.第一次获取文件名 1.txt 并添加到列表中.第二次获得值 2.txt ,但是在将文件添加到列表之后,它覆盖了值 1.txt ,并再次添加了 2.txt .现在列表值类似于 list [0]:2.txt list [1]:2.txt 有人可以帮忙吗?

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?

推荐答案

这是因为循环不断重复添加相同的对象,因此列表最终以对同一对象的多个引用结尾.

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.

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

Add projectfile = new ProjectFile() to the top of your loop to fix this problem.

这篇关于关于C#使用foreach循环将对象添加到列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆