regarding C# adding objects to list using foreach loop

前端 未结 4 2113
遇见更好的自我
遇见更好的自我 2021-01-06 17:06
foreach (string f in fileName)
{
    if (list.Where(p => p.FileName.Trim().Equals(f.Trim(), StringComparison.OrdinalIgnoreCase)).Count() == 0)
    {
        Serve         


        
相关标签:
4条回答
  • 2021-01-06 17:38

    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.

    Illustration

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

    0 讨论(0)
  • 2021-01-06 17:39

    It looks like you are creating a new string array 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. Try instantiating the array outside of your loop and then adding your value f inside.

    0 讨论(0)
  • 2021-01-06 17:51

    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.

    0 讨论(0)
  • 2021-01-06 17:56

    You seem to be reusing the same object every time in 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:

    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.

    0 讨论(0)
提交回复
热议问题