使用 List< >.FindIndex 找到要刪除的ListItem (多個查詢條件 )
問題:
要刪除List<>中特定的一筆資料(有多個查詢條件)
解法:
-
使用List<>.FIndIndex取得項目編號
-
再用List<>.RemoveAt(index)將資料刪除
KeyPoint:
List<>.FIndIndex( delegate() )
//定義員工資料型態 public class Employee { private string _Id; public string Id { get { return _Id; } set { _Id = value; } } private string _Phone; public string Phone { get { return _Phone; } set { _Phone = value; } } } protected void Page_Load(object sender, EventArgs e) { if (this.IsPostBack) return; //建立員工清單 List<Employee> Employees = new List<Employee>(); Employees.Add(new Employee { Id = "1", Phone = "07-111-1111" }); Employees.Add(new Employee { Id = "1", Phone = "0911-111-111" }); Employees.Add(new Employee { Id = "2", Phone = "0911-111-111" }); //刪除 Id= "1" Phone= "0911-111-111" 的那一筆資料 Employee delData = new Employee { Id = "1", Phone = "0911-111-111" }; RemovieList(delData, Employees); } private static void RemovieList(Employee delData, List<Employee> Employees) { //找出要刪除資料再List中的index int index = Employees.FindIndex(delegate(Employee _Employee) { //刪除條件 if (_Employee.Id != delData.Id) return false; if (_Employee.Phone != delData.Phone) return false; return true; }); //刪除資料 Employees.RemoveAt(index); }