The problem is that I tried to prepend an object to a list and it happened to me that the object wasn't added to the list at all. My code looks like this:
List<string> names = GetNames();
string defaultName = "default";
if (!names.Contains(defaultName))
names.Prepend(defaultName);
Funny thing is that when I debug the code, the Prepend() instruction was executed, but nothing happened. Therefore, I have to use List.Insert() to do the task, but I don't understand what happened here?
My name list was just a simple list that contains 4 names, nothing special, and I was using Visual studio 2017 and .Net Framework 4.7 if that be of any help.
Contains(T) Method is used to check whether an element is in the List<T> or not.
Use the AddRange() method to append a second list to an existing list. list1. AddRange(list2);
The Insert method is used to insert an item into the middle of the list.
As mentioned by the guys under the comments already Prepend
does not modify the source and same applies to all the extension methods in the Enumerable
class.
Also, mentioned in the docs:
This method does not modify the elements of the collection. Instead, it creates a copy of the collection with the new element.
The solution is to store the value returned from Prepend
rather than discarding it.
Further, if you want to find a method that actually modifies the source then use Insert
otherwise you could also create your own Prepend
extension method:
static class Extentions
{
public static void Prepend<T>(this List<T> source, T element) => source.Insert(0, element);
}
You'd use this method exactly the same way you're currently using the Enumerable.Prepend
, However you must ensure your code is actually calling this version of Prepend
instead of the one in the Enumerable
class.
You could remove confusion completely by simply renaming Prepend
to PrependToList
if deemed appropriate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With