How to remove item from list in C#?

remove object from list c#
remove item from list c# foreach
c# remove items from list based on condition
remove multiple items from list c#
remove item from array c#
remove list from list c#
remove all items from list c#
remove column from list c#

I have a list stored in resultlist as follows:

var resultlist = results.ToList();

It looks something like this:

ID FirstName  LastName
-- ---------  --------
1  Bill       Smith
2  John       Wilson
3  Doug       Berg

How do I remove ID 2 from the list?

List<T> has two methods you can use.

RemoveAt(int index) can be used if you know the index of the item. For example:

resultlist.RemoveAt(1);

Or you can use Remove(T item):

var itemToRemove = resultlist.Single(r => r.Id == 2);
resultList.Remove(itemToRemove);

When you are not sure the item really exists you can use SingleOrDefault. SingleOrDefault will return null if there is no item (Single will throw an exception when it can't find the item). Both will throw when there is a duplicate value (two items with the same id).

var itemToRemove = resultlist.SingleOrDefault(r => r.Id == 2);
if (itemToRemove != null)
    resultList.Remove(itemToRemove);

How to remove item from list in C#?, (just like in c++). It is true that you can set it's instance to null. How to Remove C# List Items. // Create a list of strings. List< string > AuthorList = new List< string >(); AuthorList.Add( "Mahesh Chand" ); AuthorList.Add( "Praveen Kumar" ); AuthorList.Add( "Raj Kumar" ); AuthorList.Add( "Nipun Tomar" ); AuthorList.Add( "Dinesh Beniwal" ); AuthorList.Remove(

resultList = results.Where(x=>x.Id != 2).ToList();

There's a little Linq helper I like that's easy to implement and can make queries with "where not" conditions a little easier to read:

public static IEnumerable<T> ExceptWhere<T>(this IEnumerable<T> source, Predicate<T> predicate)
{
    return source.Where(x=>!predicate(x));
}

//usage in above situation
resultList = results.ExceptWhere(x=>x.Id == 2).ToList();

Difference between del, remove and pop on lists, , use the Count property. if (subjects. Count == 0) Console. Removes the first occurrence of a specific object from the List<T>. public: virtual bool Remove (T item); C#. public bool Remove (T item); abstract member Remove : 'T -> bool override this.Remove : 'T -> bool. Public Function Remove (item As T) As Boolean.

Short answer: Remove (from list results)

results.RemoveAll(r => r.ID == 2); will remove the item with ID 2 in results (in place).

Filter (without removing from original list results):

var filtered = result.Where(f => f.ID != 2); returns all items except the one with ID 2

Detailed answer:

I think .RemoveAll() is very flexible, because you can have a list of item IDs which you want to remove - please regard the following example.

If you have:

class myClass {
    public int ID; public string FirstName; public string LastName;
}

and assigned some values to results as follows:

var results=new List<myClass> {
    new myClass()  { ID=1, FirstName="Bill", LastName="Smith" },
    new myClass()  { ID=2, FirstName="John", LastName="Wilson" },
    new myClass()  { ID=3, FirstName="Doug", LastName="Berg" },
    new myClass()  { ID=4, FirstName="Bill", LastName="Wilson" },
};

Then you can define a list of IDs to remove:

var removeList = new List<int>() { 2, 3 };

And simply use this to remove them:

results.RemoveAll(r => removeList.Any(a => a==r.ID));

It will remove the items 2 and 3 and keep the items 1 and 4 - as specified by the removeList. Note that this happens in place, so there is no additional assigment required.

Of course, you can also use it on single items like:

results.RemoveAll(r => r.ID==4);

where it will remove Bill with ID 4 in our example.


DotNetFiddle: Run the demo

Remove an item from an IEnumerable<T> collection, We can use the RemoveAt method to remove an item at the specified position within a List. The Remove method removes the first occurrence of a specific object from a List. The Remove method takes an item as its parameter. We can use the RemoveAt method to remove an item at the specified position within a List. For Deleting Object from a list, Remove method must be used. Remove Method deletes the value to be deleted. If the value to be deleted is more than one in the list, it removes the first value. Thi…

There is another approach. It uses List.FindIndex and List.RemoveAt.

While I would probably use the solution presented by KeithS (just the simple Where/ToList) this approach differs in that it mutates the original list object. This can be a good (or a bad) "feature" depending upon expectations.

In any case, the FindIndex (coupled with a guard) ensures the RemoveAt will be correct if there are gaps in the IDs or the ordering is wrong, etc, and using RemoveAt (vs Remove) avoids a second O(n) search through the list.

Here is a LINQPad snippet:

var list = new List<int> { 1, 3, 2 };
var index = list.FindIndex(i => i == 2); // like Where/Single
if (index >= 0) {   // ensure item found
    list.RemoveAt(index);
}
list.Dump();        // results -> 1, 3

Happy coding.

How to delete object?, Firstly, set a list and add elements. How to remove items from a list in C#? Let's say you need to delete the element “James” now. For that  C# List<T>.Remove() Method. List<T>.Remove() method is used to remove a given item from the list. Syntax: bool List<T>.Remove(T item); Parameter: It accepts an item of type T to delete from the list. Return value: It returns a Boolean value, if item deleted successfully – it returns true, if item was not found in the list – it returns false. Example:

More simplified:

resultList.Remove(resultList.Single(x => x.Id == 2));

there is no needing to create a new var object.

C# program to check whether a list is empty or not, Use Remove, RemoveRange and RemoveAt on Lists. Delete elements by value and index. Use Remove, RemoveRange and RemoveAt on Lists. Delete elements by value and index.

How to remove an Item from a C# List, The List<T> class in C# represents a collection of items that can be indexed, searched, sorted, and manipulated. List.Remove(). The Remove() method takes an item as a ​parameter and removes the What is the 'out' parameter in C#?  If I use an item in a foreach loop and I can't use the item it has to delete the item that is currently in the foreach loop. This is the code that I have right now: foreach (Line line in linelijs

List<T>.Remove(T) Method, C program to delete an element in an array: This program deletes or removes an In linked list data structure shifting isn't required only pointers are adjusted. This line data.RemoveAt(i--); is stopping the effect of increment in the iteration variable at the end of the loop, in case of item being removed from the list. It will remove the item from index at the current iteration value and then after removing the item, the iterator would be set to one less value than the current one.

How to remove items from a list in C#?, How to Pad an Integer Number With Leading Zeroes in C#?. More related articles in C#. Program to swap numbers using  What you need to do is to make a copy of the reference to the collection before iterating it, this can be accomplished by calling the.ToList () -method on the collection: foreach (var item in list.ToList ())

Comments
  • well, than maybe var itemsToRemove = resultlist.Where(r => r.Id == 2); foreach (var itemToRemove in ItemsToRemove) resultList.Remove(itemToRemove);
  • Shouldn't this be resultlist.Items.RemoveAt(1); ?
  • Another similar approach (that uses a predicate) is to use List.FindIndex/List.RemoteAt (which has the "nice" or "not so nice" feature of being a mutating operation).
  • True, but be careful about saying that List's operation is mutating. List uses an array behind the scenes, and it can recreate its array with a smaller or larger capacity when it thinks that's necessary. Usually, removal is an in-place mutation of the existing array.
  • This isnt thread safe, and for its simplicity you can just use SingleOrDefault, it doesnt need to be contained in a static method
  • Nobody said it was thread-safe (and whether it is depends on what the threads are supposed to be doing; it may in fact be preferable to give a different in-memory construct to a worker thread versus letting them all work on one concurrent collection), and the OP wants all records except the one matching the predicate, so SingleOrDefault would in fact return exactly what they don't want. The "static method" is in fact an extension method, like most of Linq, and it works whenever what you don't want (one element or many) is easier to define than what you do.