List C # in the set operation is sometimes necessary to remove a particular element of a List object or set of sequences with time it can be set to List Remove method, method Remove method signature bool Remove (T item), item List object representing a particular set, T is a generic form of the expression of C #.
(1) for example, list1 contains a set of List 1 to 10 elements, the elements 5 to be removed with the following statement:
List<int> list1 = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; list1.Remove(5);
(2) If the reference type is, depending on the need to remove the object and the reference address with the set of elements List object reference addresses match, as follows:
First, define a custom category class TestModel specific structure is as follows
public class TestModel { public int Index { set; get; } public string Name { set; get; } }
Then define a List <TestModel> List of collection, then add two elements to set, after the addition was complete removal element object Index = 1.
List<TestModel> testList = new List<ConsoleApplication1.TestModel>(); testList.Add(new ConsoleApplication1.TestModel() { Index=1, Name="Index1" }); testList.Add(new ConsoleApplication1.TestModel() { Index = 2, Name = "Index2" }); var whereRemove = testList.FirstOrDefault(t => t.Index == 1); testList.Remove(whereRemove);
After the above statement is executed successfully, testList only one element, the element object only Index = 2. If the above method Remove take the following wording, it will not be removed because although the object of all property values are the same, but the reference to the element at different addresses, not within the List collection.
var whereRemove = new TestModel() { Index = 1, Name = "Index1" }; testList.Remove(whereRemove);
Note: The text reproduced from personal bloggers station IT technology small fun house , the original link in C # List collection using the Remove method to remove the specified object _IT technology small fun house .