0

I can't get around this problem: How do I remove a string array from a list?

So the code is as follows:

List<string[]> theList = new List<string[]>();
string[] myStringarray = new string[] { a, b, c };
theList.Add(myStringarray);

The problem here is that I want the user to be able to create new strings for the string array, which then is going to be put in the List - this is already solved as you can see above.

However, how do I remove one of the string arrays in the list? I have tried transforming the List to a Jagged Array, and a couple of methods, but I just can't seem to find a solution to this particular problem.

Cœur
  • 37,241
  • 25
  • 195
  • 267
ErkBla
  • 11
  • 1
  • 2
  • 1
    `.RemoveAt(int Index)` or `.Remove(T item)` or `.ExceptWhere()`? – DirtyBit Apr 22 '18 at 08:22
  • Could you please further elaborate on the use-case? There is a `List.Remove`, `List.RemoveAt`, `List.RemoveAll` which can be used, but you'd probably have to find the correct array to remove first. – Zdeněk Jelínek Apr 22 '18 at 08:24
  • Possible duplicate of [c# - How to remove item from list?](https://stackoverflow.com/questions/10018957/c-sharp-how-to-remove-item-from-list) – PSK Apr 22 '18 at 08:24
  • 1
    In case your code (re)creates a new array with the same elements as the original array in the lists, you cannot use list.Remove(item) directly with the newly created array, as this would not remove the original array in the list. Because the newly created array is an object different from the original array in the list (despite both containing the same elements). In such a case, you would need to iterate over the arrays in the list and compare their content/elements (and their order, if necessary) to find the array object in the list you want to remove... –  Apr 22 '18 at 08:28
  • Well, the RemoveAt(int Index) wouldn't work because the index is "flexible" and Remove() complains that string [] can't be converted to string (which would be the search string the user inputs). – ErkBla Apr 22 '18 at 19:44

5 Answers5

3

You can use Remove() method if you already have a reference to the string array that you want to remove like the following:

 List<string[]> theList = new List<string[]>();
 string[] myStringarray = new string[] { "a", "b", "c" };
 theList.Add(myStringarray);

 //remove myStringarray from the main list
 theList.Remove(myStringarray);

However if you are getting the items from the user and you want to search for an array that contains these elements and remove them, I recommend creating an extension method like the following:

public static class ExtensionMethods
{
    public static string[] FindAndRemove(this ICollection<string[]> list, string[] items)
    {
        string[] removedList = null;
        foreach (var stringArray in list)
        {
            if (stringArray.SequenceEqual(items))
            {
                removedList = stringArray;
                break;
            }
        }
        if (removedList != null)
        {
            list.Remove(removedList);
        }
        return removedList;
    }
}

Which is mainly search for the first array that its elements equal the passed element in item array (the parameter) and remove it, you can further improve this method and make it remove all the lists that satisfy the condition as following:

 public static class ExtensionMethods
 {
    public static int FindAndRemove(this List<string[]> list, string[] items)
    {
        return list.RemoveAll(arr => arr.SequenceEqual(items));
    }
 }

Here I have used RemoveAll from Linq library, which remove all the lists that meet the given condition. Note that SequecnceEqual also exists inside linq library and used to:

Determines whether two sequences are equal by comparing the elements by using the default equality comparer for their type.

Mahmoud Heretani
  • 555
  • 1
  • 6
  • 17
  • Your find and remove method will error as soon as you remove the item as you have modified the collection you are enumerating over. – BlythMeister Apr 22 '18 at 09:03
  • Hmmm, your correct in case I was removing the items inside foreach loop, but as you can see in the first version I am not removing the item until I am done with my searching loop – Mahmoud Heretani Apr 22 '18 at 09:07
0

I would use List.RemoveAll (https://msdn.microsoft.com/en-us/library/wdka673a(v=vs.110).aspx)

Remove all takes a predicate function which will allow you to find any items you want to remove.

For example if the containing array has a specific value in it.

BlythMeister
  • 299
  • 1
  • 12
0

You can simply use Remove function:

List<string[]> theList = new List<string[]>();
string[] myStringarray = new string[] { a, b, c };
theList.Add(myStringarray);
theList.Remove(myStringarray);

Remove() Removes the the specified element.
RemoveAt() Removes the element at the specified index.
RemoveAll() Removes all the elements that match with the supplied predicate function.

If you want to check if the arrays are match. you can use:

for(int i=0;i<theList.Count();i++)
{
    bool areEqual =theList[i].SequenceEqual(newStringArray);
    if(areEqual)
      theList.RemoveAt(i);
}
BlythMeister
  • 299
  • 1
  • 12
לבני מלכה
  • 15,925
  • 2
  • 23
  • 47
0

For the case RemoveAll with a predicate I offerthe following (removing by avalue in arrays)

        List<string[]> theList = new List<string[]>();
        string[] myStringarray = new string[] { "a", "b", "c" };
        theList.Add(myStringarray);
        theList.Add(new string[] { "d", "e", "f" });            
        theList.RemoveAll(zz => zz.Where(xx => xx == "b").Count() > 0);
-2
  • Take iterator .........

    Block quote

    Iterator itr =list.iterator(); while(itr.hasNext()){ //some condition itr.remove(); }

    Block quote

    .......

  • 2
    ......... Block quote ......... ??? I understand that it is weekend, but ......... and why use an iterator instead of using for/foreach (in conjunction with `break` or similar) or some Linq query to find (and then remove) the element... –  Apr 22 '18 at 08:33
  • Also, List does not have a method called `iterator()`. Nor any other method providing an Iterator type. List is an IEnumerable, providing an IEnumerator. C# ain't Java... –  Apr 22 '18 at 08:38
  • Block quote nothing just posted from android app so it came unwantedly. But if you are not sure about index of array then u can remove from iterator also if you try to remove from for each/for loop it will throw concurrent modification exception. – Varun Srivastawa Apr 22 '18 at 08:38
  • No, it will only throw an exception if you continue with the for/foreach loop after removing the element. If you exit the loop when removing the element, no exception. Also, your "iterator" example suffers the exactly same "problem" and would require the same treatment (exiting the loop early when removing), because the removal operation would invalidate the enumerator/iterator. –  Apr 22 '18 at 08:39
  • My bad what i mentioned that is java code not c# code. – Varun Srivastawa Apr 22 '18 at 08:43