C#中创建单项列表的快捷方式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/462793/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Shortcut for creating single item list in C#
提问by Ryan Ische
In C#, is there an inline shortcut to instantiate a List<T> with only one item.
在 C# 中,是否有内联快捷方式来实例化只有一项的 List<T>。
I'm currently doing:
我目前正在做:
new List<string>( new string[] { "title" } ))
Having this code everywhere reduces readability. I've thought of using a utility method like this:
到处都有此代码会降低可读性。我想过使用这样的实用方法:
public static List<T> SingleItemList<T>( T value )
{
return (new List<T>( new T[] { value } ));
}
So I could do:
所以我可以这样做:
SingleItemList("title");
Is there a shorter / cleaner way?
有更短/更清洁的方法吗?
Thanks.
谢谢。
采纳答案by M4N
Simply use this:
只需使用这个:
List<string> list = new List<string>() { "single value" };
You can even omit the () braces:
你甚至可以省略 () 大括号:
List<string> list = new List<string> { "single value" };
Update: of course this also works for more than one entry:
更新:当然这也适用于多个条目:
List<string> list = new List<string> { "value1", "value2", ... };
回答by Michael Meadows
Use an extension method with method chaining.
使用带有方法链的扩展方法。
public static List<T> WithItems(this List<T> list, params T[] items)
{
list.AddRange(items);
return list;
}
This would let you do this:
这会让你这样做:
List<string> strings = new List<string>().WithItems("Yes");
or
或者
List<string> strings = new List<string>().WithItems("Yes", "No", "Maybe So");
Update
更新
You can now use list initializers:
您现在可以使用列表初始值设定项:
var strings = new List<string> { "This", "That", "The Other" };
See http://msdn.microsoft.com/en-us/library/bb384062(v=vs.90).aspx
请参阅http://msdn.microsoft.com/en-us/library/bb384062(v=vs.90).aspx
回答by Rune Grimstad
You can also do
你也可以这样做
new List<string>() { "string here" };
回答by Jon Skeet
Michael's idea of using extension methods leads to something even simpler:
Michael 使用扩展方法的想法导致了一些更简单的事情:
public static List<T> InList<T>(this T item)
{
return new List<T> { item };
}
So you could do this:
所以你可以这样做:
List<string> foo = "Hello".InList();
I'm not sure whether I like it or not, mind you...
我不确定我是否喜欢它,介意你...
回答by Brian Rasmussen
I would just do
我只会做
var list = new List<string> { "hello" };
回答by Jon Skeet
A different answer to my earlier one, based on exposure to the Google Java Collections:
根据对Google Java Collections 的了解,对我之前的一个不同的回答:
public static class Lists
{
public static List<T> Of<T>(T item)
{
return new List<T> { item };
}
}
Then:
然后:
List<string> x = Lists.Of("Hello");
I advise checking out the GJC - it's got lots of interesting stuff in. (Personally I'd ignore the "alpha" tag - it's only the open source version which is "alpha" and it's based on a very stable and heavily used internal API.)
我建议查看 GJC - 它有很多有趣的东西。(我个人会忽略“alpha”标签 - 它只是“alpha”的开源版本,它基于非常稳定且大量使用的内部 API .)
回答by Joel Coehoorn
var list = new List<string>(1) { "hello" };
Very similar to what others have posted, except that it makes sure to only allocate space for the single item initially.
与其他人发布的内容非常相似,除了它确保最初只为单个项目分配空间。
Of course, if you know you'll be adding a bunch of stuff later it may not be a good idea, but still worth mentioning once.
当然,如果你知道你以后会添加一堆东西,这可能不是一个好主意,但仍然值得一提。
回答by Squirrel
For a single item enumerable in java it would be Collections.singleton("string");
对于 Java 中可枚举的单个项目,它将是 Collections.singleton("string");
In c# this is going to be more efficient than a new List:
在 c# 中,这将比新列表更有效:
public class SingleEnumerator<T> : IEnumerable<T>
{
private readonly T m_Value;
public SingleEnumerator(T value)
{
m_Value = value;
}
public IEnumerator<T> GetEnumerator()
{
yield return m_Value;
}
IEnumerator IEnumerable.GetEnumerator()
{
yield return m_Value;
}
}
but is there a simpler way using the framework?
但是有没有更简单的使用框架的方法?
回答by Gert Arnold
I've got this little function:
我有这个小功能:
public static class CoreUtil
{
public static IEnumerable<T> ToEnumerable<T>(params T[] items)
{
return items;
}
}
Since it doesn't prescribe a concrete return type this is so generic that I use it all over the place. Your code would look like
由于它没有规定具体的返回类型,因此它非常通用,以至于我到处都使用它。你的代码看起来像
CoreUtil.ToEnumerable("title").ToList();
But of course it also allows
但当然它也允许
CoreUtil.ToEnumerable("title1", "title2", "title3").ToArray();
I often use it in when I have to append/prepend one item to the output of a LINQ statement. For instance to add a blank item to a selection list:
当我必须在 LINQ 语句的输出中附加/添加一项时,我经常使用它。例如,将空白项目添加到选择列表:
CoreUtil.ToEnumerable("").Concat(context.TrialTypes.Select(t => t.Name))
Saves a few ToList()
and Add
statements.
保存一些ToList()
和Add
语句。
(Late answer, but I stumbled upon this oldie and thought this could be helpful)
(迟到的答案,但我偶然发现了这个老歌,并认为这可能会有所帮助)
回答by Ruben Bartelink
Inspired by the other answers (and so I can pick it up whenever I need it!), but with naming/style aligned with F# (which has a standard singleton
function per data structure*):
受到其他答案的启发(因此我可以在需要时随时拿起它!),但命名/样式与 F#(singleton
每个数据结构都有一个标准函数*)一致:
namespace System.Collections.Generic
{
public static class List
{
public static List<T> Singleton<T>(T value) => new List<T>(1) { value };
}
}
* except for ResizeArray
itself of course, hence this question :)
*ResizeArray
当然除了它自己,因此这个问题:)
In practice I actuallyname it Create
to align with other helpers I define such as Tuple.Create
, Lazy.Create
[2], LazyTask.Create
etc:
在实践中,我实际上将它命名Create
为与我定义的其他助手保持一致,例如Tuple.Create
,Lazy.Create
[2]LazyTask.Create
等:
namespace System.Collections.Generic
{
public static class List
{
public static List<T> Create<T>(T value) => new List<T>(1) { value };
}
}
[2]
[2]
namespace System
{
public static class Lazy
{
public static Lazy<T> Create<T>(Func<T> factory) => new Lazy<T>(factory);
}
}