C# 简化在列表中查找元素的过程,可能使用LINQ
我有以下代码:C# 简化在列表中查找元素的过程,可能使用LINQ,c#,linq,C#,Linq,我有以下代码: class TestClass { public string StringValue { get; set; } public int IntValue { get; set; } } class MainClass { private readonly List<TestClass> MyList; public MainClass() { MyList =
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);
}
}
class测试类
{
公共字符串字符串值{
获得;设置;
}
公共int值{
获得;设置;
}
}
类主类
{
私有只读列表MyList;
公共类()
{
MyList=新列表();
}
public void removestclass(字符串strValue)
{
int ndx=0;
而(ndx
我想知道的是,是否有一种更简单的方法,可能是使用LINQ,来替换2个removestclass
函数中的while
循环,而不是像我这样迭代每个元素?您可以使用:
您可能还希望处理找不到元素的情况:
int i = myList.FindIndex(x => x.StringValue == strValue);
if (i != -1)
{
myList.RemoveAt(i);
}
我会这样做:
public void RemoveTestClass(string strValue)
{
MyList.RemoveAll(item => item.StringValue.Equals(strValue));
}
以及:
更新:
如果只想删除第一次发生:
public void RemoveTestClass(int intValue)
{
var itemToRemove = MyList.FirstOrDefault(item => item.InValue == intValue);
if (itemToRemove != null)
{
MyList.Remove(itemToRemove);
}
}
我认为最简单的方法是找到符合条件的第一项,然后使用List.Remove:
myList.Remove(myList.FirstorDefault(x=>x.StringValue == stringValue))
因为
Remove
在找不到项目时不会引发异常,所以上面的工作正常。除非您允许在列表中有空值,这将被删除,而且我认为在列表中有空值并不太好。RemoveAll将删除所有项目,不仅仅是第一个。你也可以使用andList.Find
而不是List.FindIndex
你不能吗?@TimSchmelter但是Find如果找不到匹配的项,就会抛出一个execption。@Fischermaen:但是@Mark已经处理了i=-1
的情况。您还可以处理List.Find
为null
@TimSchmelter:是的,您可以这样做,但在最坏的情况下,需要在整个列表上迭代两次。(很抱歉,我第一次阅读时误解了您的评论)。这是有道理的,那么最好使用FindIndex
public void RemoveTestClass(int intValue)
{
var itemToRemove = MyList.FirstOrDefault(item => item.InValue == intValue);
if (itemToRemove != null)
{
MyList.Remove(itemToRemove);
}
}
myList.Remove(myList.FirstorDefault(x=>x.StringValue == stringValue))