Quick way to turn object into single-element list?

混江龙づ霸主 提交于 2019-12-10 15:17:37

问题


What is the quickest in C# 2.0 to create a one-element list out of a single object?

eg:

MyObject obj = new MyObject();
List<MyObject> list = new List<MyObject> { obj };    // is this possible?

回答1:


Your sample code

List<MyObject> list = new List<MyObject> { obj };

uses a collection initializer, which was not available in C# 2.0. You could use an array initializer, instead:

List<MyObject> list = new List<MyObject>(new MyObject[] { obj });

Or, just make the list and add the object:

List<MyObject> list = new List<MyObject>(1);
list.Add(obj);

Note that "singleton" usually refers to the singleton pattern; as you see from the comments, it's confusing to use that term to refer to a collection containing one element.




回答2:


You could create the following extension and just call it on any object you want to create a list of itself.

The only down side is that it would pollute the extension space... So I would only do this if you found yourself using it often.

public static partial class Extensions
{
    public static List<T> ToListOfSelf<T>(this T item)
    {
        return new List<T>() { item };
    }
}

e.g. myObject.ToListOfSelf();



来源:https://stackoverflow.com/questions/13998343/quick-way-to-turn-object-into-single-element-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!