Home > Back-end >  Break foreach C#
Break foreach C#

Time:11-24

I created a foreach that reads me the various fields inside a .csv file and inserts them into an xml file. I wanted to know if there was the possibility of blocking the cycle after a series of lines read (eg 10). how can I do?

List<string> lines = File.ReadAllLines(path).ToList();
lines.RemoveAt(0);
        

XmlTextWriter writer = new XmlTextWriter(savepath, Encoding.UTF8);

writer.WriteStartDocument();
writer.WriteStartElement("DC8_Recipe");

foreach (var line in lines){
    var csvItem = line.Split(';');
           
    writer.WriteStartElement("DC8_Recipe");
    writer.WriteAttributeString("PlantNo", "01");
    writer.WriteAttributeString("FactoryNo", "01");
    writer.WriteAttributeString("No", csvItem[0].Replace('"', ' '));
    writer.WriteAttributeString("Name", csvItem[2]);
    writer.WriteAttributeString("ShortName", csvItem[3]);
    writer.WriteEndElement();
    writer.WriteStartElement("RecipeSetValueRow");
    writer.WriteAttributeString("SetValue", csvItem[12]);
    writer.WriteStartElement("Material");
    writer.WriteAttributeString("No", csvItem[10]);
    writer.WriteEndElement();
    writer.WriteEndElement();

}

writer.WriteEndElement();
writer.WriteEndDocument();
writer.Close();

CodePudding user response:

There are multiple ways to do what you are asking.

#1 - decalre a counter int counter=0 and use this variable to as a condition for breaking out of the loop if ((counter ) > 10 ) {break;}

#2 (the recommended way) - Use .Take(10) calling Take() on IEnumerable will return the specified number of contiguous elements

copy past the code below and try it for yourself

List<string> lines = File.ReadAllLines(path).ToList();
            lines.RemoveAt(0);


            XmlTextWriter writer = new XmlTextWriter(savepath, Encoding.UTF8);

            writer.WriteStartDocument();
            writer.WriteStartElement("DC8_Recipe");

            foreach (var line in lines.Take(10))
            {
                var csvItem = line.Split(';');

                writer.WriteStartElement("DC8_Recipe");
                writer.WriteAttributeString("PlantNo", "01");
                writer.WriteAttributeString("FactoryNo", "01");
                writer.WriteAttributeString("No", csvItem[0].Replace('"', ' '));
                writer.WriteAttributeString("Name", csvItem[2]);
                writer.WriteAttributeString("ShortName", csvItem[3]);
                writer.WriteEndElement();
                writer.WriteStartElement("RecipeSetValueRow");
                writer.WriteAttributeString("SetValue", csvItem[12]);
                writer.WriteStartElement("Material");
                writer.WriteAttributeString("No", csvItem[10]);
                writer.WriteEndElement();
                writer.WriteEndElement();

            }

            writer.WriteEndElement();
            writer.WriteEndDocument();
            writer.Close();

        }
  • Related