Home > Software design >  How to check and insert values to list c#
How to check and insert values to list c#

Time:07-23

After accessing the local file, I need to check and add the missing coloumn(walmart) before converting it to xml.I confirm data is available in the csv file. Currently I am getting "System.InvalidOperationException: 'Collection was modified; enumeration operation may not execute"

string[] vs = File.ReadAllLines(@"C:/Users/Raw.csv");

var lines = new List <String>();
            
lines = vs.ToList();

foreach (var check in lines)
{
    if (!check.Contains("Walmart"))
    {
        lines.Insert(0,"Walmart");
    }
}
foreach (var shw in lines)
{
    Console.WriteLine(shw);
}

CodePudding user response:

Techically, if you want just amend your current code you can count how many Walmarts we should add:

var lines = File
  .ReadLines(@"C:/Users/Raw.csv")
  .ToList();

int walmartsToAdd = 0;

foreach (var check in lines) 
  if (!check.Contains("Walmart"))
    walmartsToAdd  = 1;

if (walmartsToAdd > 0)
  lines.InsertRange(0, Enumerable.Repeat("Walmart", walmartsToAdd));

foreach (var shw in lines)
  Console.WriteLine(shw);

But it seems, that you should modify lines: abc,def => Walmart,abc,def. If it's your case you can just add Select

var lines = File
  .ReadLines(@"C:/Users/Raw.csv")
  .Select(line => line.StartsWith("Walmart,")  ? line : $"Walmart,{line}")
  .ToList();

foreach (var shw in lines)
  Console.WriteLine(shw);

CodePudding user response:

You can't modify the source Enumerable while iterating on it. I always imagine that the enumerator has inside a current index and if for example, the change would delete all the members the index wouldn't make any sense anymore. The easy solution is to iterate on something else / make a copy.

Here instead of lines you can try iterating on the variable 'vs'.

var vs = File.ReadAllLines(@"C:/Users/Raw.csv");

var lines = vs.ToList();

foreach (var check in vs)
{
    if (!check.Contains("Walmart"))
    {
        lines.Insert(0, "Walmart");
    }
}

foreach (var shw in lines)
{
    Console.WriteLine(shw);
}
  • Related