簡體   English   中英

從列表中刪除項目 <string[]> 或獲取任何位置的任何項目的索引

[英]Remove item from List<string[]> or get index of any item at any position

我正在嘗試從List<string[]>刪除項目,但是remove屬性不起作用,但是如果我使用RemoveAt(0) (任何int硬編碼值),那么它正在起作用...可能是問題。 誰能幫我?

這是我的代碼...

List<string[]> ipcol1 = new List<string[]>();
ipcol1.Add(new string[] { "test1" });
ipcol1.Add(new string[] { "test2" });
ipcol1.Add(new string[] { "test3" });
ipcol1.Add(new string[] { "test4" });
ipcol1.Remove(new string[] { "test1" });

int i = ipcol1.IndexOf(new string[] { "test4" });
ipcol1.RemoveAt(i);

或者,如果我嘗試獲取特定項目的索引,則結果為(-1)。如果我可以獲取該問題的索引,則我的問題可以解決...請幫助我。

比較數組時必須使用SequenceEqual

  List<string[]> ipcol1 = new List<string[]>();
  ipcol1.Add(new string[] { "test1" });
  ipcol1.Add(new string[] { "test2" });
  ipcol1.Add(new string[] { "test3" });
  ipcol1.Add(new string[] { "test4" });

  ipcol1.RemoveAll(array => array.SequenceEqual(new string[] { "test1" }));

或者(如果要刪除數組中某處包含"test1"任何記錄):

  ipcol1.RemoveAll(array => array.Any(item => item == "test1")));

原因是如果兩個數組具有相同的引用,則它們相等:

  string[] array1 = new string[0];
  string[] array2 = array1;
  string[] array3 = new string[0];

  // "Yes" - array1 and array2 reference to the instance
  Console.WriteLine((array1 == array2) ? "Yes" : "No");
  // "No" - array1 and array3 are references to different instances
  Console.WriteLine((array1 == array3) ? "Yes" : "No");

  // "Yes" - array1 and array3 are equal sequences
  Console.WriteLine((array1.SequenceEqual(array3)) ? "Yes" : "No");

數組是引用類型。 以下代碼失敗,因為您正在比較兩個單獨實例的引用。

ipcol1.Remove(new string[] { "test1" });

您可以使用SequenceEqual比較集合。

暫無
暫無

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

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