
Question:
I have the following code:
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);
}
}
What I would like to know is if there is a simpler way, perhaps using LINQ, to replace the while
loops in the 2 RemoveTestClass
functions, rather then iterating through each element, like I'm doing?
You can use <a href="http://msdn.microsoft.com/en-us/library/x1xzf2ca.aspx" rel="nofollow">List<T>.FindIndex
</a>:
myList.RemoveAt(MyList.FindIndex(x => x.StringValue == strValue));
You may also want to handle the case where the element is not found:
int i = myList.FindIndex(x => x.StringValue == strValue);
if (i != -1)
{
myList.RemoveAt(i);
}
Answer2:Simplest possible way I can think is finding first item, which matches the criteria and then use List.Remove to do it:
myList.Remove(myList.FirstorDefault(x=>x.StringValue == stringValue))
because Remove
doesn't throw an exception when it can't find the item, above works fine. except you permited to have null values in list, which will be deleted, and I think it's not so good to have them in list.
I would do it in that way:
public void RemoveTestClass(string strValue)
{
MyList.RemoveAll(item => item.StringValue.Equals(strValue));
}
and:
public void RemoveTestClass(int intValue)
{
MyList.RemoveAll(item => item.IntValue == intValue);
}
Update:
If you only want to remove the first occurrance:
public void RemoveTestClass(int intValue)
{
var itemToRemove = MyList.FirstOrDefault(item => item.InValue == intValue);
if (itemToRemove != null)
{
MyList.Remove(itemToRemove);
}
}