简体   繁体   English

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

[英]regarding C# adding objects to list using foreach loop

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. 我在string[] filename中有两个文件1.txt2.txt I am comparing these files with db and getting values into lstgAFPFileInfo . 我将这些文件与db进行比较,并将值转换为lstgAFPFileInfo The first time it got the filename 1.txt and added to list. 它第一次获得文件名1.txt并添加到列表中。 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 . 第二次获得值2.txt但是在将文件添加到列表后,它将覆盖值1.txt并再次添加2.txt Now the list values are like this list[0]:2.txt and list[1]: 2.txt Can anyone help on this? 现在列表值就像这个list[0]:2.txtlist[1]: 2.txt任何人都可以帮忙吗?

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. projectfile = new ProjectFile()添加到循环的顶部以解决此问题。

You seem to be reusing the same object every time in projectfile . 您似乎每次都在projectfile重用相同的对象。 Even after it has been added to the list you have the same object being referenced in the list and in the variable so when you update its properties you update it in both places. 即使将其添加到列表中,您也会在列表和变量中引用相同的对象,因此在更新其属性时,您将在两个位置更新它。

What you need is just to have a line at the beginning of your foreach saying something like: 你需要的只是在你的foreach开头说一句话:

projectfile = new ProjectFileObject();

This will create a new instance that is totally separate from the one already added to the list. 这将创建一个与已添加到列表中的实例完全分离的新实例。

It should be noted that depending on what you have done with the projectfile object before a more complicated solution may be required but this highlights your basic problem. 应该注意的是,在可能需要更复杂的解决方案之前,取决于您对projectfile对象所做的操作,但这突出了您的基本问题。

Becasue you're adding the same instance each time, just overwriting its properties. 假设您每次都添加相同的实例,只是覆盖其属性。 You need 你需要

projectfile = new WhateverClassNameProjectFileIs();

at the top of your innermost foreach loop. 在最里面的foreach循环的顶部。

It looks like you are creating a new string array foreach f in filename. 看起来你正在创建一个新的字符串数组foreach f in filename。

foreach (string f in fileName)
{
lstgAFPFileInfo = GetFilesFromSourceServer(new string[] { f }, ServerpathID, SearchOption.TopDirectoryOnly).ToList();

Thus, each iteration through the foreach, only the value of f at that time is created in the array. 因此,通过foreach的每次迭代,只在该数组中创建f的值。 Try instantiating the array outside of your loop and then adding your value f inside. 尝试在循环外部实例化数组,然后在内部添加值f。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM