我有以下代码:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
我想知道的是,如果有一种更简单的方法,也许使用LINQ,来替换while2个RemoveTestClass函数中的循环,而不是迭代遍历每个元素,就像我正在做的那样?
你可以使用List<T>.FindIndex:
myList.RemoveAt(MyList.FindIndex(x => x.StringValue == strValue));
Run Code Online (Sandbox Code Playgroud)
您可能还想处理未找到元素的情况:
int i = myList.FindIndex(x => x.StringValue == strValue);
if (i != -1)
{
myList.RemoveAt(i);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
136 次 |
| 最近记录: |