Problem
I have the following list in resultlist:
var resultlist = results.ToList();
This is what it looks like:
ID FirstName LastName
-- --------- --------
1 Bill Smith
2 John Wilson
3 Doug Berg
What is the procedure for removing ID 2 from the list?
Asked by Nate Pet
Solution #1
There are two ways to utilize ListT>.
If you know the item’s index, you can use RemoveAt(int index). Consider the following scenario:
resultlist.RemoveAt(1);
Remove(T item): Remove(T item): Remove(T item): Remove(T item): Remove(T
var itemToRemove = resultlist.Single(r => r.Id == 2);
resultList.Remove(itemToRemove);
When you’re not sure whether or not an object exists, use SingleOrDefault. If there is no item, SingleOrDefault will return null (Single will throw an exception if it cannot find the item). When a value is duplicated, both will throw an exception (two items with the same id).
var itemToRemove = resultlist.SingleOrDefault(r => r.Id == 2);
if (itemToRemove != null)
resultList.Remove(itemToRemove);
Answered by Wouter de Kort
Solution #2
Short answer: Get rid of it (from list results)
results. RemoveAll(r => r.ID == 2) removes the item with ID 2 from the list of results (in place).
Filter (without removing anything from the original list):
filtered = result, var filtered = result, var filtered = result, var All items except the one with ID 2 are returned when where(f => f.ID!= 2); is used.
Detailed answer:
I believe. Because you might have a list of item IDs that you want to remove, RemoveAll() is quite flexible – see the example below.
If you have:
class myClass {
public int ID; public string FirstName; public string LastName;
}
and assigned the following values to the outcomes:
var results = new List<myClass> {
new myClass { ID=1, FirstName="Bill", LastName="Smith" }, // results[0]
new myClass { ID=2, FirstName="John", LastName="Wilson" }, // results[1]
new myClass { ID=3, FirstName="Doug", LastName="Berg" }, // results[2]
new myClass { ID=4, FirstName="Bill", LastName="Wilson" } // results[3]
};
Then you can create a list of IDs that you want to get rid of:
var removeList = new List<int>() { 2, 3 };
And just use this to get rid of them:
results.RemoveAll(r => removeList.Any(a => a==r.ID));
The items 2 and 3 will be removed, while items 1 and 4 will be kept, as indicated by the removeList. It’s worth noting that this occurs in real time, so no additional planning is required.
Of course, you may use it on individual items as well, such as:
results.RemoveAll(r => r.ID==4);
In our case, it will erase Bill with ID 4.
Last but not least, lists include an indexer, which means they may be accessed like a dynamic array, for example, results[3] will provide the fourth member in the results list (because the first element has the index 0, the 2nd has index 1 etc).
So, if you want to eliminate all items with the same first name as the fourth element of the results list, simply follow these steps:
results.RemoveAll(r => results[3].FirstName == r.FirstName);
Note that only John and Doug will remain on the list after that; Bill will be deleted (the first and last element in the example). The list will automatically shrink until there are only two members remaining – and hence the largest permitted index after performing RemoveAll in this example is 1 (results). 1) (Count() – 1) (Count() – 1) (Count() – 1) (Count
Some trivia: You can develop a local function using this knowledge.
void myRemove() { var last = results.Count() - 1;
results.RemoveAll(r => results[last].FirstName == r.FirstName); }
What do you think will happen if this function is called twice? Like
myRemove(); myRemove();
The first call will take Bill out of the first and last positions, the second call will take Doug out of the list, and only John Wilson will remain.
Note that you can now use results[1] instead of var last = results in C# Version 8. results[last]: Count() – 1; and Count() – 1
void myRemove() => results.RemoveAll(r => results[^1].FirstName == r.FirstName);
As a result, the local variable last is no longer required (see indices and ranges). Furthermore, because it is a one-liner, you can omit the curly braces and instead use =>. Look here for a complete list of Cnew #’s features.
Run the demo on DotNetFiddle.
Answered by Matt
Solution #3
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();
Answered by KeithS
Solution #4
You don’t say what kind of list you’re working with, but the general List can utilise the RemoveAt(index) or Remove(obj) methods:
// Remove(obj)
var item = resultList.Single(x => x.Id == 2);
resultList.Remove(item);
// RemoveAt(index)
resultList.RemoveAt(1);
Answered by mgnoonan
Solution #5
More simplified:
resultList.Remove(resultList.Single(x => x.Id == 2));
It’s not necessary to make a new var object.
Answered by Javier Andres Caicedo
Post is based on https://stackoverflow.com/questions/10018957/how-to-remove-item-from-list-in-c