2011-10-26 37 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不拋出一個異常時,它無法找到該項目,上述工作正常。除非你讓列表中有空值,這些值將被刪除,我認爲把它們放在列表中並不是那麼好。

相關問題