0

I am using a stringsplitting mechanism for comma separated strings,and using a foreach loop for looping each item, So if I want to remove an item what can I do?

string lyrsct = drow1["lyricist"].ToString();
var delimiters = new[] {','}; 
var lyrsct1 = lyrsct.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
foreach (var item in lyrsct1)
{
    if()
        {
         .........i need to remove from here.....
        }                 
}

I want to remove item inside the if loop.

hakkeem
  • 185
  • 1
  • 4
  • 13
  • 7
    possible duplicate of [c# remove item from list](http://stackoverflow.com/questions/10018957/c-sharp-remove-item-from-list) – NASSER Aug 22 '15 at 13:11
  • You can not remove from list **inside foreach loop**. instead use a for loop and handle index changes correctly. if you remove item from `lyrsct1` inside foreach loop you get InvalidOperationException : [Collection was modified](http://stackoverflow.com/questions/2024179/c-sharp-collection-was-modified-enumeration-operation-may-not-execute) – M.kazem Akhgary Aug 22 '15 at 13:20
  • Which condition do you want? Any example input? – NASSER Aug 22 '15 at 13:24
  • @X-TECH notice that `lyrsct1` and `lyrsct` is not a list. its an array – M.kazem Akhgary Aug 22 '15 at 13:26
  • Provide input as you assigned to `lyrsct` and what is the expected output? – NASSER Aug 22 '15 at 13:27
  • 1
    possible duplicate of [Can you remove an item from a List<> whilst iterating through it in C#](http://stackoverflow.com/questions/1541777/can-you-remove-an-item-from-a-list-whilst-iterating-through-it-in-c-sharp) – Christo S. Christov Aug 22 '15 at 13:46

6 Answers6

0
foreach (var item in lyrsct1)    
{    
      if (//item's condition)
      {
         lyrsct1.Remove(item );        
      }                   
}
NASSER
  • 5,900
  • 7
  • 38
  • 57
0

This would be my solution for removing items given that you have some condition on which to act.

I am removing '7' from lists.

    var condition = "7";
    string lists = "1,2,3,4,5,6,7,7,8,9";
    var delimiter = new[] {','};
    var splitlist = lists.Split(delimiter,StringSplitOptions.RemoveEmptyEntries).ToList();
    var newList = new List<string>();

   foreach (var item in splitlist.Where(x => !x.Equals(condition)))
        {
            newList.Add(item);
        }
   OR

   var newList = splitlist.Where(x => !x.Equals(condition)).ToList();
PatWill
  • 11
  • 2
0

Try this

var result = new List<string>();
foreach (var item in lyrsct1.Where(x => !x.Contains("example text"))) // you can also compare values here instead of contains or !Contains (not contains)
{    
    result.Add(item);
}

OR

var lyrsct1 = lyrsct.Split(delimiters, StringSplitOptions.RemoveEmptyEntries)
              .Where(x => !x.Contains("example text")).ToList();
NASSER
  • 5,900
  • 7
  • 38
  • 57
0

You can not modify an array. you have to convert lyrsct1 into list.

also you can not modify collection inside foreach loop when you are iterating over it. so use for loop instead

        string lyrsct = drow1["lyricist"].ToString();
        var delimiters = new[] { ',' };
        var lyrsct1 = lyrsct.Split(delimiters, StringSplitOptions.RemoveEmptyEntries).ToList(); // List is modifiable.
        for (int i = 0; i < lyrsct1.Length; i++)
        {
            var item = lyrsct1[i];
            if ()
            { 
                int indexToRemove = something; // index of item that should be removed
                lyrsct1.Remove(indexToRemove);
                if(indexToRemove <= i) i--; // correct the indexing
            }
        }

from this answer:

The foreach statement is used to iterate through the collection to get the information that you want, but can not be used to add or remove items from the source collection to avoid unpredictable side effects. If you need to add or remove items from the source collection, use a for loop.

Also take a look at :Collection was modified. enumeration operation may not execute

Community
  • 1
  • 1
M.kazem Akhgary
  • 18,645
  • 8
  • 57
  • 118
0

The easiest way to filter out some elements is to use .Where LINQ method. I assume that you you want to get an array of strings as a result:

string lyrsct = drow1["lyricist"].ToString();
var delimiters = new[] {','}; 
var lyrsct1 = lyrsct.Split(delimiters, StringSplitOptions.RemoveEmptyEntries)
    .Where(item => !condition(item).ToArray();
Alexey
  • 1,299
  • 11
  • 10
0

You can create a new List containing only filtered elements:

string lyrsct = drow1["lyricist"].ToString();
var delimiters = new[] {','}; 
var lyrsct1 = lyrsct.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);

List<string> newList = new List<string>(lyrcst1.Where(elem => !predicate(elem)));

Check the constructor taking IEnumerable<T>: https://msdn.microsoft.com/en-us/library/fkbw11z0.aspx

w.b
  • 11,026
  • 5
  • 30
  • 49