简体   繁体   English

为什么Linq Prepend()无法与List一起使用 <T> ?

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

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. 有趣的是,当我调试代码时,执行了Prepend()指令,但没有任何反应。 Therefore, I have to use List.Insert() to do the task, but I don't understand what happened here? 因此,我必须使用List.Insert()来完成任务,但是我不明白这里发生了什么?

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. 我的名字列表只是一个包含4个名字的简单列表,没什么特别的,如果有帮助,我正在使用Visual Studio 2017和.Net Framework 4.7。

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. 就像伙计们在评论中提到的那样, Prepend不会修改源代码,并且同样适用于Enumerable类中的所有扩展方法。

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. 解决方案是存储从Prepend返回的值,而不是丢弃它。

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: 此外,如果要查找实际修改源代码的方法,请使用“ Insert否则还可以创建自己的Prepend扩展方法:

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. 您将使用与当前使用Enumerable.Prepend完全相同的方法来使用此方法,但是必须确保您的代码实际上是在调用此版本的Prepend而不是Enumerable类中的版本。

You could remove confusion completely by simply renaming Prepend to PrependToList if deemed appropriate. 如果认为适当,您可以简单地将Prepend重命名为PrependToList来完全消除混乱。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM