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.

5
  • 1
    .RemoveAt(int Index) or .Remove(T item) or .ExceptWhere()? Commented Apr 22, 2018 at 8:22
  • Could you please further elaborate on the use-case? There is a List<T>.Remove, List<T>.RemoveAt, List<T>.RemoveAll which can be used, but you'd probably have to find the correct array to remove first. Commented Apr 22, 2018 at 8:24
  • Possible duplicate of c# - How to remove item from list? Commented Apr 22, 2018 at 8: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... Commented Apr 22, 2018 at 8: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). Commented Apr 22, 2018 at 19:44

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Your find and remove method will error as soon as you remove the item as you have modified the collection you are enumerating over.
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
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.

Comments

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);

Comments

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);
}

1 Comment

for more methods to comparing two string arrays:stackoverflow.com/questions/17212254/…
-2
  • Take iterator .........

    Block quote

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

    Block quote

    .......

5 Comments

......... 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...
Also, List<T> does not have a method called iterator(). Nor any other method providing an Iterator type. List<T> is an IEnumerable<T>, providing an IEnumerator<T>. C# ain't Java...
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.
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.
My bad what i mentioned that is java code not c# code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.