簡體   English   中英

如何:從列表中刪除項目<string>

[英]How to: Remove an item from a List<string>

如何:從列表中刪除項目

我有以下代碼片段...

companies.Remove(listView_Test.SelectedItem.ToString());

有一個listView包含(比方說)3個沒有名字的項目,只有Content為“A”,“B”和“C”。 現在,當我選擇該listView一個項目時,我再次單擊一個按鈕,該按鈕運行包含Remove() / RemoveAt() 現在我想刪除List<string> myList的行,其中該行與所選項的Content相同。

編輯: Flow Flow OverFlow的解決方案

int index = companies.IndexOf(companyContent);
companies.RemoveAt(index);

您必須從列表中獲取要刪除的對象的索引,然后您可以:

//Assuming companies is a list 
companies.RemoveAt(i);

要獲取可以使用的項目的索引:

companies.IndexOf("Item");

或者使用帶有條件語句的for循環:

for (int i = 0; i < companies.Count; i++) {
   // if it is List<String>
   if (companies[i].equals("Something")) {
         companies.RemoveAt(i);   
   }
}

您可以按已知位置或項目中的內容刪除項目。

public static void Main()
{
    List<Object> items = new List<Object>();
    items.Add("test1");
    items.Add("test2");
    items.Add("test3");

foreach(var a in items)
    Console.WriteLine(a.ToString());
Console.WriteLine("--");

items.RemoveAt(1); // remove object at position 1, in this case "test2"

foreach(var a in items)
    Console.WriteLine(a.ToString());
Console.WriteLine("--");

items.RemoveAll(x => ((string) x) == "test1"); // LAMBDA query to remove by a condition

foreach(var a in items)
    Console.WriteLine(a.ToString());
}

產量

test1
test2
test3
--
test1
test3
--
test3

我真的無法理解你的問題是什么,但這里有一些可能對你有幫助的參考:

如果您的問題與訪問當前所選列表視圖項的文本有關,請參閱ListViewItem的Text屬性: http//msdn.microsoft.com/en-us/library/system.windows.forms.listviewitem.text(v=vs。 110)的.aspx

請參閱List.Remove如果您的問題與從通用列表中刪除元素有關: http//msdn.microsoft.com/en-us/library/cd666k3e( v = vs.110) .aspx

public int FindItem(List<string> haystack, string needle)
{ for (int i = 0; i < haystack.Count; i++) 
      if (haystack[i] == needle) return i;
  return -1;
}


try {
     companies.Remove(FindItem(companies, listView_Test.SelectedItem.ToString() ) );
    } catch {  /* not found, no problem.. */ } 

暫無
暫無

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

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