简化定位列表中的元素,可能使用LINQ
我有以下代码:
class TestClass { public string StringValue { get; set; } public int IntValue { get; set; } } class MainClass { private readonly List MyList; public MainClass() { MyList = new List(); } 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,来替换2个RemoveTestClass
函数中的while
循环,而不是迭代遍历每个元素,就像我在做什么?
您可以使用List
:
myList.RemoveAt(MyList.FindIndex(x => x.StringValue == strValue));
您可能还想处理未找到元素的情况:
int i = myList.FindIndex(x => x.StringValue == strValue); if (i != -1) { myList.RemoveAt(i); }
我能想到的最简单的方法是找到符合条件的第一项,然后使用List.Remove来做:
myList.Remove(myList.FirstorDefault(x=>x.StringValue == stringValue))
因为Remove
无法在找不到项目时抛出exception,上面的工作正常。 除了你有权在列表中有空值,这将被删除,我认为将它们列入列表并不是那么好。
我会这样做:
public void RemoveTestClass(string strValue) { MyList.RemoveAll(item => item.StringValue.Equals(strValue)); }
和:
public void RemoveTestClass(int intValue) { MyList.RemoveAll(item => item.IntValue == intValue); }
更新:
如果您只想删除第一个出现的情况:
public void RemoveTestClass(int intValue) { var itemToRemove = MyList.FirstOrDefault(item => item.InValue == intValue); if (itemToRemove != null) { MyList.Remove(itemToRemove); } }