簡體   English   中英

如何從C#的列表中刪除字符串數組?

[英]How do I remove a String Array from a List in C#?

我無法解決此問題:如何從列表中刪除字符串數組?

所以代碼如下:

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

這里的問題是我希望用戶能夠為字符串數組創建新的字符串,然后將其放入列表中-如您在上面所看到的,這已經得到解決。

但是,如何刪除列表中的字符串數組之一? 我已經嘗試過將List轉換為鋸齒數組和幾種方法,但似乎無法找到解決此特定問題的方法。

如果已經具有要刪除的字符串數組的引用,則可以使用Remove()方法,如下所示:

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

但是,如果要從用戶那里獲取項目,並且想要搜索包含這些元素的數組並將其刪除,則我建議創建一個如下擴展方法:

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

這主要是搜索第一個數組,該數組的元素等於item數組中傳遞的元素(參數),然后將其刪除,您可以進一步改進此方法,使其刪除所有滿足條件的列表,如下所示:

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

在這里,我使用了Linq庫中的RemoveAll,它刪除了所有滿足給定條件的列表。 請注意,SequecnceEqual也存在於linq庫中,並用於:

通過使用元素的默認相等比較器比較元素,確定兩個序列是否相等。

我會使用List.RemoveAll( https://msdn.microsoft.com/zh-cn/library/wdka673a ( v= vs.110).aspx)

“全部刪除”具有謂詞功能,可讓您找到要刪除的所有項目。

例如,如果包含數組中具有特定值。

您可以簡單地使用Remove功能:

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

Remove()刪除指定的元素。
RemoveAt()刪除指定索引處的元素。
RemoveAll()刪除與提供的謂詞函數匹配的所有元素。

如果要檢查數組是否匹配 您可以使用:

for(int i=0;i<theList.Count();i++)
{
    bool areEqual =theList[i].SequenceEqual(newStringArray);
    if(areEqual)
      theList.RemoveAt(i);
}

對於帶有謂詞的RemoveAll,我提供以下內容(按數組中的值刪除)

        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);
  • 拿迭代器.........

    塊報價

    迭代器itr = list.iterator(); while(itr.hasNext()){//一些條件itr.remove(); }

    塊報價

    .......

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM