我有以下代码用于在我的列表中添加值。
public class Temp {
public object Id { get; set; }
public object Amount { get; set; }
public object TrasactionDateTime { get; set; }
}
private List<Temp> list = new List<Temp>();
添加
list.Add(new Temp{ Id = GetData["Id"], Amount = GetData["Amount"], TrasactionDateTime = GetData["TransactionDateTime"] });
如何删除列表中的项目?
例如
list.Remove(Id = "1");
答案 0 :(得分:3)
您需要使用Id = "1"
从列表中找到该项目,然后将其删除。
var item = list.FirstOrDefault(r=> r.Id.ToString() == "1");
if(item != null)
list.Remove(item);
您还可以使用List<T>.RemoveAt()
答案 1 :(得分:1)
尝试使用.Find
匹配指定条件定义的条件的第一个元素 谓词,如果找到;否则,类型T的默认值。
List<Temp> list = new List<Temp>();
var f = list.Find(c => c.Id == 1);
if (f == null) return;
var x = list.Remove(f);
答案 2 :(得分:1)
list.RemoveAll(s => s.Id == "1");
答案 3 :(得分:1)
list.RemoveAll (s => s.Id == "1"); // remove by condition
请注意这将删除具有给定ID的所有临时符。
如果你需要删除id找到的第一个temp,首先使用First方法找到他,然后为实例调用Remove:
var firstMatch = list.First (s => s.Id == "1");
list.Remove (firstMatch);
如果你想在删除之前确保只有一个具有给定id的临时表,请以类似的方式使用Single:
var onlyMatch = list.Single (s => s.Id == "1");
list.Remove (onlyMatch);
请注意,如果没有一个项与谓词匹配,则单次调用将失败。