Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Linq Prepend() does not work with List<T>?

Tags:

c#

.net

linq

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.

like image 976
Thế Long Avatar asked Dec 25 '18 09:12

Thế Long


People also ask

How to check if list contains item c#?

Contains(T) Method is used to check whether an element is in the List<T> or not.

Can you add a list to another list C#?

Use the AddRange() method to append a second list to an existing list. list1. AddRange(list2);

What does list insert Do C#?

The Insert method is used to insert an item into the middle of the list.


1 Answers

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.

like image 195
Ousmane D. Avatar answered Sep 19 '22 17:09

Ousmane D.