for循环的替代方案

时间:2016-04-18 09:19:39

标签: c#

我正在尝试使用for循环来循环一些对象。

for (int i = 0; i < PersonalIdentityNumber.Count; i++)
{
    var personnummer = PersonalIdentityNumber[i];
    var fornamn = FirstName[i];
    var efternamn = LastName[i];
    var lankod = LanKod[i];
    var kommunkod = Kommunkod[i];
    var postNr = PostNr[i];
    var medborgarskapslandKod = MedborgarskapslandKod[i];
}

得到错误:

  

指数超出范围。它不能是负面的,必须更小   比众人大小。

我收到错误的原因是因为对象postNr的计数为21,其中主要PersonalIdentityNumber为24。

在这种情况下,我可以使用替代for循环的替代方案吗? for循环的问题是对象不能小于主要对象(在本例中为PersonalIdentityNumber

更新3

我的整个代码。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Xml;
using System.Data;
using System.Xml.Serialization;
using System.IO;

namespace TESTMAPPNING2
{
    class Program
{
        static void Main(string[] args)
        {
            //try
            //{

            List<FolkbokforingspostTYPE> deserializedList = new List<FolkbokforingspostTYPE>();
            deserializedList = Deserialize<List<FolkbokforingspostTYPE>>();


            var myPersons = Deserialize<List<FolkbokforingspostTYPE>>()
                .Select(x => new Person
                {
                    PersonalIdentityNumber = x.Personpost.PersonId.PersonNr,
                    LastName = x.Personpost.Namn.Efternamn,
                    FirstName = x.Personpost.Namn.Fornamn,
                    NationalRegistrationCountyCode = x.Personpost.Folkbokforing.LanKod,
                    NationalRegistrationMunicipalityCode = x.Personpost.Folkbokforing.KommunKod,
                    CitizenshipCode = x.Personpost.Medborgarskap.MedborgarskapslandKod
                    // and so on
                });


           // var PersonalIdentityNumber = deserializedList.Select(item => item.Personpost.PersonId.PersonNr).ToList();
           // var FirstName = deserializedList.Select(item => item.Personpost.Namn.Fornamn).ToList();

           // var LastName = deserializedList.Select(item => item.Personpost.Namn.Efternamn).ToList();
           // var LanKod = deserializedList.Select(item => item.Personpost.Folkbokforing.LanKod).ToList();
           // var Kommunkod = deserializedList.Select(item => item.Personpost.Folkbokforing.KommunKod).ToList();

           //// var UtdelAdress2 = deserializedList.Select(item => item.Personpost.Adresser.Folkbokforingsadress.Utdelningsadress2).ToList();
           // var PostNr = deserializedList.Select(item => item.Personpost.Adresser.Folkbokforingsadress != null ? item.Personpost.Adresser.Folkbokforingsadress.PostNr : null);

           // //var PostOrt = deserializedList.Select(item => item.Personpost.Adresser.Folkbokforingsadress.Postort).ToList();

           // //var FodelselanKod = deserializedList.Select(item => item.Personpost.Fodelse.HemortSverige.FodelselanKod).ToList();

           // //var Fodelseforsamling = deserializedList.Select(item => item.Personpost.Fodelse.HemortSverige.Fodelseforsamling).ToList();

           // var MedborgarskapslandKod = deserializedList.Select(item => item.Personpost.Medborgarskap.MedborgarskapslandKod).ToList();

           // var Medborgarskapsdatum = deserializedList.Select(item => item.Personpost.Medborgarskap.Medborgarskapsdatum).ToList();


            //var zipped = PersonalIdentityNumber.Zip(FirstName, Tuple.Create);

            //     foreach (var tuple in zipped)
            //     {
            //         //Console.WriteLine(tuple.Item1);
            //         //Console.WriteLine(tuple.Item2);
            //     }

            //Console.WriteLine(PersonalIdentityNumber.Count());

            //for (int i = 0; i < PersonalIdentityNumber.Count; i++)
            //{
            //    var personnummer = PersonalIdentityNumber[i];
            //    var fornamn = FirstName[i];
            //        var efternamn = LastName[i];

            //        var lankod = LanKod[i];
            //        var kommunkod = Kommunkod[i];
            //        var utdelAdress2 = UtdelAdress2[i];
            //        var postNr = PostNr[i];
            //        var postOrt = PostOrt[i];
            //        var fodelselanKod = FodelselanKod[i];
            //        var fodelseforsamling = Fodelseforsamling[i];
            //        var medborgarskapslandKod = MedborgarskapslandKod[i];
            //        var medborgarskapsdatum = Medborgarskapsdatum[i];
            //         use your variables


            //}

            //Console.WriteLine(PersonalIdentityNumber.Count());

            //foreach (var i in PersonalIdentityNumber)
            //{
            //    Console.WriteLine("Personnummer: " + i);

            //    foreach(var a in FirstName)
            //    {
            //        Console.WriteLine("Namn: " + a);
            //    }







            string connetionString = null;


            SqlDataAdapter adpter = new SqlDataAdapter();
            DataSet ds = new DataSet();
            XmlReader xmlFile;



            connetionString = "Data Source=tsrv2062;Initial Catalog=Bums;User ID=BumsUser;Password=2tusen7Bums";


            xmlFile = XmlReader.Create("navetout.xml", new XmlReaderSettings());
            ds.ReadXml(xmlFile);


            using (var connection = new SqlConnection(connetionString))
            {
                connection.Open();



                DateTime datum = DateTime.Now;

                SqlCommand command1 = new SqlCommand("UPDATE Seamen SET FirstName = @FirstName, LastName = @LastName, NationalRegistrationCountyCode = @NationalRegistrationCountyCode, NationalRegistrationMunicipalityCode = @NationalRegistrationMunicipalityCode, CitizenshipCode = @CitizenshipCode, LastChangedDate = @LastChangedDate WHERE PersonalIdentityNumber = @PersonalIdentityNumber", connection);

                foreach (Person p in myPersons)
                {



                    //var personnummer = PersonalIdentityNumber[i];
                    //var fornamn = FirstName[i];
                    //var efternamn = LastName[i];
                    //var lankod = LanKod[i];
                    //var kommunkod = Kommunkod[i];
                    //var utdelAdress2 = UtdelAdress2[i];
                    //var postNr = PostNr[i];
                    //var postOrt = PostOrt[i];
                    //var fodelselanKod = FodelselanKod[i];
                    //var fodelseforsamling = Fodelseforsamling[i];
                    //var medborgarskapslandKod = MedborgarskapslandKod[i];
                    // var medborgarskapsdatum = Medborgarskapsdatum[i];


                    //command1.Parameters.Clear();
                    command1.Parameters.AddWithValue("@PersonalIdentityNumber", p.PersonalIdentityNumber);
                    command1.Parameters.AddWithValue("@FirstName", p.FirstName);
                    command1.Parameters.AddWithValue("@LastName", p.LastName);
                    command1.Parameters.AddWithValue("@NationalRegistrationCountyCode", p.NationalRegistrationCountyCode);
                    command1.Parameters.AddWithValue("@NationalRegistrationMunicipalityCode", p.NationalRegistrationMunicipalityCode);
                    ////command1.Parameters.AddWithValue("@NationalRegistrationDistributionAddress2", utdelAdress2);
                    ////command1.Parameters.AddWithValue("@NationalRegistrationPostCode", postNr);
                    ////command1.Parameters.AddWithValue("@NationalRegistrationCity", postOrt);
                    ////command1.Parameters.AddWithValue("@BirthCountyCode", fodelselanKod);
                    ////command1.Parameters.AddWithValue("@BirthParish", fodelseforsamling);
                    command1.Parameters.AddWithValue("@CitizenshipCode", p.CitizenshipCode);
                    //// command1.Parameters.AddWithValue("@CitizenshipDate", medborgarskapsdatum);
                    command1.Parameters.AddWithValue("@LastChangedDate", datum);



                    command1.ExecuteNonQuery();

                    Console.WriteLine(p.PersonalIdentityNumber);


                }
            }

            Console.WriteLine("Done");
        }

            //}// Put a break-point here, then mouse-over PersonalIdentityNumber...  deserializedList contains everything if you need it
        //   catch (Exception)
        //    {

        //        throw;
        //    }
        //    Console.ReadKey();
        //}

   class Person {
       public string PersonalIdentityNumber { get; set; }
       public string FirstName { get; set; }
       public string LastName { get; set; }
       public string NationalRegistrationCountyCode { get; set; }
       public string NationalRegistrationMunicipalityCode { get; set; }
       public string CitizenshipCode { get; set; }
}

    private static T Deserialize<T>() where T : new()
    {
        // Create an instance of T
        T ReturnListOfT = CreateInstance<T>();


        // Create a new file stream for reading the XML file
        using (FileStream ReadFileStream = new FileStream("navetout.xml", FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            // Construct a XmlSerializer and use it  
            // to serialize the data from the stream.
            XmlSerializer SerializerObj = new XmlSerializer(typeof(T));
            try
            {
                // Deserialize the hashtable from the file
                ReturnListOfT = (T)SerializerObj.Deserialize(ReadFileStream);
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("Failed to serialize. Reason: {0}", ex.Message));
            }

        }
        // return the Deserialized data.
        return ReturnListOfT;
    }

    // function to create instance of T
    public static T CreateInstance<T>() where T : new()
    {
        return (T)Activator.CreateInstance(typeof(T));
    }





}

[XmlRoot(ElementName = "Sekretessmarkering")]
public class Sekretessmarkering
{
    [XmlAttribute(AttributeName = "nil", Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
    public string Nil { get; set; }
}

[XmlRoot(ElementName = "PersonId")]
public class PersonId
{
    [XmlElement(ElementName = "PersonNr")]
    public string PersonNr { get; set; }

    [XmlElement(ElementName = "TilldelatPersonNrSamordningsNr")]
    public string Tilltalsnamnsmarkering { get; set; }
}

[XmlRoot(ElementName = "HanvisningsPersonNr")]
public class HanvisningsPersonNr
{
    [XmlAttribute(AttributeName = "nil", Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
    public string Nil { get; set; }
}

[XmlRoot(ElementName = "Mellannamn")]
public class Mellannamn
{
    [XmlAttribute(AttributeName = "nil", Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
    public string Nil { get; set; }
}

[XmlRoot(ElementName = "Aviseringsnamn")]
public class Aviseringsnamn
{
    [XmlAttribute(AttributeName = "nil", Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
    public string Nil { get; set; }
}

[XmlRoot(ElementName = "Namn")]
public class Namn
{
    [XmlElement(ElementName = "Tilltalsnamnsmarkering")]
    public string Tilltalsnamnsmarkering { get; set; }
    [XmlElement(ElementName = "Fornamn")]
    public string Fornamn { get; set; }
    [XmlElement(ElementName = "Mellannamn")]
    public Mellannamn Mellannamn { get; set; }
    [XmlElement(ElementName = "Efternamn")]
    public string Efternamn { get; set; }
    [XmlElement(ElementName = "Aviseringsnamn")]
    public Aviseringsnamn Aviseringsnamn { get; set; }
}

[XmlRoot(ElementName = "ForsamlingKod")]
public class ForsamlingKod
{
    [XmlAttribute(AttributeName = "nil", Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
    public string Nil { get; set; }
}

[XmlRoot(ElementName = "Folkbokforing")]
public class Folkbokforing
{
    [XmlElement(ElementName = "Folkbokforingsdatum")]
    public string Folkbokforingsdatum { get; set; }
    [XmlElement(ElementName = "LanKod")]
    public string LanKod { get; set; }
    [XmlElement(ElementName = "KommunKod")]
    public string KommunKod { get; set; }
    [XmlElement(ElementName = "ForsamlingKod")]
    public ForsamlingKod ForsamlingKod { get; set; }
    [XmlElement(ElementName = "Fastighetsbeteckning")]
    public string Fastighetsbeteckning { get; set; }
    [XmlElement(ElementName = "FiktivtNr")]
    public string FiktivtNr { get; set; }
}

[XmlRoot(ElementName = "CareOf")]
public class CareOf
{
    [XmlAttribute(AttributeName = "nil", Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
    public string Nil { get; set; }
}

[XmlRoot(ElementName = "Utdelningsadress1")]
public class Utdelningsadress1
{
    [XmlAttribute(AttributeName = "nil", Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
    public string Nil { get; set; }
}

[XmlRoot(ElementName = "Folkbokforingsadress")]
public class Folkbokforingsadress
{
    [XmlElement(ElementName = "CareOf")]
    public CareOf CareOf { get; set; }
    [XmlElement(ElementName = "Utdelningsadress1")]
    public Utdelningsadress1 Utdelningsadress1 { get; set; }
    [XmlElement(ElementName = "Utdelningsadress2")]
    public string Utdelningsadress2 { get; set; }
    [XmlElement(ElementName = "PostNr")]
    public string PostNr { get; set; }
    [XmlElement(ElementName = "Postort")]
    public string Postort { get; set; }
}

[XmlRoot(ElementName = "Riksnycklar")]
public class Riksnycklar
{
    [XmlElement(ElementName = "FastighetsId")]
    public string FastighetsId { get; set; }
    [XmlElement(ElementName = "AdressplatsId")]
    public string AdressplatsId { get; set; }
    [XmlElement(ElementName = "LagenhetsId")]
    public string LagenhetsId { get; set; }
}

[XmlRoot(ElementName = "Adresser")]
public class Adresser
{
    [XmlElement(ElementName = "Folkbokforingsadress")]
    public Folkbokforingsadress Folkbokforingsadress { get; set; }
    [XmlElement(ElementName = "Riksnycklar")]
    public Riksnycklar Riksnycklar { get; set; }
}

[XmlRoot(ElementName = "HemortSverige")]
public class HemortSverige
{
    [XmlElement(ElementName = "FodelselanKod")]
    public string FodelselanKod { get; set; }
    [XmlElement(ElementName = "Fodelseforsamling")]
    public string Fodelseforsamling { get; set; }
}

[XmlRoot(ElementName = "Fodelse")]
public class Fodelse
{
    [XmlElement(ElementName = "HemortSverige")]
    public HemortSverige HemortSverige { get; set; }
}

[XmlRoot(ElementName = "Medborgarskap")]
public class Medborgarskap
{
    [XmlElement(ElementName = "MedborgarskapslandKod")]
    public string MedborgarskapslandKod { get; set; }
    [XmlElement(ElementName = "Medborgarskapsdatum")]
    public string Medborgarskapsdatum { get; set; }
}

[XmlRoot(ElementName = "Personpost")]
public class Personpost
{
    [XmlElement(ElementName = "PersonId")]
    public PersonId PersonId { get; set; }
    [XmlElement(ElementName = "HanvisningsPersonNr")]
    public HanvisningsPersonNr HanvisningsPersonNr { get; set; }
    [XmlElement(ElementName = "Namn")]
    public Namn Namn { get; set; }
    [XmlElement(ElementName = "Folkbokforing")]
    public Folkbokforing Folkbokforing { get; set; }
    [XmlElement(ElementName = "Adresser")]
    public Adresser Adresser { get; set; }
    [XmlElement(ElementName = "Fodelse")]
    public Fodelse Fodelse { get; set; }
    [XmlElement(ElementName = "Medborgarskap")]
    public Medborgarskap Medborgarskap { get; set; }
}

[XmlRoot(ElementName = "FolkbokforingspostTYPE")]
public class FolkbokforingspostTYPE
{
    [XmlElement(ElementName = "Sekretessmarkering")]
    public Sekretessmarkering Sekretessmarkering { get; set; }
    [XmlElement(ElementName = "Personpost")]
    public Personpost Personpost { get; set; }
}
}

3 个答案:

答案 0 :(得分:5)

您正在寻找解决问题症状的方法,但您可以更好地解决实际问题:您需要停止使用parallel arrays

创建一个类来保存对象的所有属性,即

class PersonalInfo {
    public int PersonalIdentityNumber { get; }
    public string FirstName { get; }
    public string LastName { get; }
    ... // and so on
}

制作PersonalInfo类对象的集合。现在,您可以使用for循环遍历集合,而不必担心一个数组比另一个数组短,或者甚至使用foreach循环来遍历元素而不使用索引。

注意:如果您对阵列的不同步感到好奇,就会发生这种情况:

var PostNr = deserializedList
    .Where(item => item.Personpost.Adresser.Folkbokforingsadress != null)
    .Select(item => item.Personpost.Adresser.Folkbokforingsadress.PostNr)
    .ToList();

Where子句拒绝某些null条目,因此数组不再是并行的。您可以通过删除Where并为某些null生成PostNr来解决此问题,即

var PostNr = deserializedList
    .Select(item => item.Personpost.Adresser.Folkbokforingsadress?.PostNr)
    .ToList();   //                                              ^

(即#C#6语法;如果您的C#是早期版本,则可以使用显式null检查。

答案 1 :(得分:1)

我首先会考虑您应用的实际设计。您应该将表示数据库中实体的所有数据捆绑到新类中,例如Person

class Person {
    public int PersonalIdentityNumber { get; }
    public string FirstName { get; }
    public string LastName { get; }
    // ...
}

当您使用XmlSerialization获取数据时,您甚至不需要所有那些混乱的数组,并且可以简单地反序列化为Person的实例 - 无论是否设置了PostNr - 标记。

StreamReader reader = new StreamReader(path);
Person p = (Person) serializer.Deserialize(reader);
reader.Close();

这会自动将null(或类型的默认值为)分配给未在xml中设置的属性。

编辑:如果您已经有一个类型FolkbokforingspostTYPE的列表,其中包含您需要的所有信息,为什么要将值存储在单独的列表中呢?你可以简单地使用它:

var myPersons = Deserialize<List<FolkbokforingspostTYPE>>()
    .Select(x => new Person 
        {
            PersonalIdentityNumber = x.Personpost.PersonId.PersonNr,
            LastName = x.Personpost.Namn.Efternamn,
            FirstName = x.Personpost.Namn.ForNamn
            NationalRegistrationDistributionAddress2 = (Personpost.Adresser == null || Personpost.Adresser.Folkbokforingsadress == null) ?
                null: 
                Personpost.Adresser.Folkbokforingsadress.Utdelningsadress2)
         });

EDIT2:使用此列表,您现在可以简单地创建和执行您的Sql语句:

foreach(Person p in myPersons) 
{
    command1.Parameters.Clear();
    command1.Parameters.AddWithValue("@PersonalIdentityNumber", p.PersonalIdentityNumber);
    command1.Parameters.AddWithValue("@FirstName", p.FirstName);
    command1.Parameters.AddWithValue("@LastName", p.LastName);

    command1.ExecuteNonQuery();
    Console.WriteLine(personnummer);
}

答案 2 :(得分:-3)

您可以尝试使用带有personalIdentityNumber作为控制值的foreach循环

foreach(var element in PersonalIdentityNumber){
 if(int < element){ 
 do something; 
 int++;
 }
}