2011-10-26 32 views
3

我有以下代码:简化列表中查找一个元素,可能使用LINQ

class TestClass 
{ 
    public string StringValue { 
     get; set; 
    } 
    public int IntValue { 
     get; set; 
    } 
} 

class MainClass 
{ 
    private readonly List<TestClass> MyList; 

    public MainClass() 
    { 
     MyList = new List<TestClass>(); 
    } 

    public void RemoveTestClass(string strValue) 
    { 
     int ndx = 0; 

     while (ndx < MyList.Count) 
     { 
      if (MyList[ndx].StringValue.Equals(strValue)) 
       break; 
      ndx++; 
     } 
     MyList.RemoveAt(ndx); 
    } 

    public void RemoveTestClass(int intValue) 
    { 
     int ndx = 0; 

     while (ndx < MyList.Count) 
     { 
      if (MyList[ndx].IntValue == intValue) 
       break; 
      ndx++; 
     } 
     MyList.RemoveAt(ndx); 
    } 
} 

我想知道的是,如果有一个更简单的方法,可能使用LINQ,更换while循环在2 RemoveTestClass功能,而不是迭代通过每个元素,就像我在做什么?

回答

6

您可以使用List<T>.FindIndex

myList.RemoveAt(MyList.FindIndex(x => x.StringValue == strValue)); 

您可能还需要处理,其中元素没有找到的情况下:

int i = myList.FindIndex(x => x.StringValue == strValue); 
if (i != -1) 
{ 
    myList.RemoveAt(i); 
} 
+0

你也可以使用[List.Remove](http://msdn.microsoft.com/en-us/library/cd666k3e%28v=VS.100%29.aspx)和'List.Find'代替' List.FindIndex'不是吗? –

+0

@TimSchmelter但是如果找不到匹配的项目,find会抛出一个错误。 – Fischermaen

+0

@Fischermaen:但@Mark已经处理了'i = -1'的情况。你也可以处理'List.Find'为'null'的情况。 –

2

我会做的那样:

public void RemoveTestClass(string strValue) 
{ 
    MyList.RemoveAll(item => item.StringValue.Equals(strValue)); 
} 

和:

public void RemoveTestClass(int intValue) 
{ 
    MyList.RemoveAll(item => item.IntValue == intValue); 
} 

更新:

如果你只是想删除的第一occurrance:

我能想到
public void RemoveTestClass(int intValue) 
{ 
    var itemToRemove = MyList.FirstOrDefault(item => item.InValue == intValue); 
    if (itemToRemove != null) 
    { 
     MyList.Remove(itemToRemove); 
    } 
}  
+3

RemoveAll将删除所有的项目,而不仅仅是第一个。 –

+0

@MarkByers你是对的。我已更正了示例。 – Fischermaen

3

最简单的方式是找到的第一个项目,它匹配的条件,然后用List.Remove做它:

myList.Remove(myList.FirstorDefault(x=>x.StringValue == stringValue)) 

因为Remove不抛出一个异常时,它无法找到该项目,上述工作正常。除非你让列表中有空值,这些值将被删除,我认为把它们放在列表中并不是那么好。

相关问题