2013-02-22 175 views
-1

我有下面的代码在我的列表中添加一个值。列表中删除项目

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

可能的重复[从C#中的通用列表中删除项目?](http://stackoverflow.com/questions/4903893/delete-item-from-generic-list-in-c) – horgh 2013-02-22 06:28:24

回答

3

你需要找到从Id = "1"列表项目,然后将其删除。

var item = list.FirstOrDefault(r=> r.Id.ToString() == "1"); 
if(item != null) 
    list.Remove(item); 

您还可以根据使用List<T>.RemoveAt()

+2

或使用'RemoveAll'使用谓词来指定要移除的元素。 – 2013-02-22 06:16:59

+0

@BrianRasmussen,你是对的,我以为OP想要删除单个项目, – Habib 2013-02-22 06:20:03

+1

为什么我们使用'RemoveAll'让我们假设Id是唯一的+1 :) – spajce 2013-02-22 06:22:59

1

尝试使用匹配由指定 谓词定义的条件​​

的第一个元素的索引中删除的项目,如果发现;否则,对于类型T的默认值

List<Temp> list = new List<Temp>(); 
var f = list.Find(c => c.Id == 1); 
if (f == null) return; 
var x = list.Remove(f); 
1
list.RemoveAll(s => s.Id == "1"); 
1
list.RemoveAll (s => s.Id == "1"); // remove by condition 

注意这将删除所有临时工带指定id。

如果您需要删除通过ID找到的第一个温度,首先使用第一种方法来找到他,然后调用该实例中删除:

var firstMatch = list.First (s => s.Id == "1"); 
list.Remove (firstMatch); 

如果你想确保只有一个临时用除去他之前给定的ID,以类似的方式使用单:

var onlyMatch = list.Single (s => s.Id == "1"); 
list.Remove (onlyMatch); 

注意,如果不是正好有一个项目相匹配的谓语单呼失败。