Simplifying Locating an element in a list, perhaps using LINQ


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); }


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)); }


public void RemoveTestClass(int intValue) { MyList.RemoveAll(item => item.IntValue == intValue); }


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); } }


  • equation solver in C segmentation fault
  • Convert numbers to text-formatted numbers
  • Delete from ListBox items in a Loop
  • How to programmatically retrieve UUID of root disk partition in OS X?
  • d3 onclick to get the specific path/bar reference
  • Remove an item from a list box causes a Catastrophic Failure?
  • dc.js: Reducing rows in data table
  • How to fail Phing without triggering backtrace
  • Linq Full Outer Join on Two Objects
  • How to get the index of element in the List in c#
  • Disabling sound of embedded flash object with html
  • Haskell: function composition with anonymous/lambda function
  • What does the TypeScript “lib” option really do?
  • Most efficient way to replace lowest list values in dataframe in R
  • Changing a global variable in C
  • How to populate html table with info from list in django
  • Detecting # in Scheme list
  • Prevent page break in text block with iText, XMLWorker
  • Shouldn't else be indented in the below code
  • How can I mock ui-router's resolve values when testing a state's configuration?
  • Primefaces ManyCheckbox inside ui:repeat calls setter method only for last loop
  • Using Sax parsing to edit and write XML in VB6
  • C++ pointer value changes with static_cast
  • How integrated is Collada to OpenGL ES
  • WPF - CanExecute dosn't fire when raising Commands from a UserControl
  • Time complexity of a program which involves multiple variables
  • debug library loaded with ctypes using gdb
  • Admob requires api-13 or later can I not deploy on old API-8 phones?
  • Record samples being played with OpenAL
  • Django: Count of Group Elements
  • output of program is not same as passed argument
  • Does CUDA 5 support STL or THRUST inside the device code?
  • Sending data from AppleScript to FileMaker records
  • MySQL WHERE-condition in procedure ignored
  • Statically linking a C++ library to a C# process using CLI or any other way
  • Why winpcap requires both .lib and .dll to run?
  • EntityFramework adding new object to nested object collection
  • Checking variable from a different class in C#
  • failed to connect to specific WiFi in android programmatically
  • How can I use threading to 'tick' a timer to be accessed by other threads?