简体   繁体   English

列表未正确填充

[英]List not populating correctly

Every time I run this code, certlist reads in the first set of values and writes them successfully to the list. 每次我运行此代码时,certlist都会读取第一组值并将它们成功写入到列表中。 When it runs through the loop again the next set of values overwrites the first one and creates a second one. 当它再次遍历循环时,下一组值将覆盖第一个值并创建第二个值。 The end result is two identically values inside the list. 最终结果是列表内的两个相同的值。

Any help with why it would overwrite the first value and how to fix it would be great. 对于它为何会覆盖第一个值以及如何修复它的任何帮助都将非常有用。

        foreach (var certcard in xdoc.Root.Element("Diver").Element("Certifications").Elements("Certification_Card"))
        {
            cert.Level = certcard.Element("Level").Value;
            cert.Agency = certcard.Element("Agency").Value;
            cert.Number = certcard.Element("Number").Value;
            cert.Date = Convert.ToDateTime(certcard.Element("Date").Value);

            certlist.Add(cert);
        }

Your original code was only missing the declaration of cert: 您的原始代码仅缺少cert声明:

    foreach (var certcard in xdoc.Root.Element("Diver").Element("Certifications")
        .Elements("Certification_Card"))
    {
        var cert = new Cert();
        cert.Level = certcard.Element("Level").Value;
        cert.Agency = certcard.Element("Agency").Value;
        cert.Number = certcard.Element("Number").Value;
        cert.Date = Convert.ToDateTime(certcard.Element("Date").Value);

        certlist.Add(cert);
    }

Similarly, you could do this without a loop using Linq: 同样,您可以使用Linq进行无循环操作:

certlist.AddRange(xdoc.Root.Element("Diver")
    .Element("Certifications")
    .Elements("Certification_Card")
    .Select(c => new Cert
    {
        Level = c.Element("Level").Value,
        Agency = c.Element("Agency").Value,
        Number = c.Element("Number").Value,
        Date = Convert.ToDateTime(c.Element("Date").Value)
    }));

Try this : 尝试这个 :

    foreach (var certcard in xdoc.Root.Element("Diver").Element("Certifications")
        .Elements("Certification_Card"))
    {
        certlist.Add(new Cert() 
        { 
            Level = certcard.Element("Level").Value, 
            Agency = certcard.Element("Agency").Value, 
            Number = certcard.Element("Number").Value, 
            Date = Convert.ToDateTime(certcard.Element("Date").Value) 
        });
    }

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

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