[英]Arrays.asList( ... ) in .Net
I am looking for the simplest way to write the following Java code我正在寻找编写以下 Java 代码的最简单方法
Arrays.asList(1L);
in .Net在.Net
Thanks谢谢
int[] a = new int[] { 1, 2, 3, 4, 5 };
List<int> list = a.ToList(); // Requires LINQ extension method
//Another way...
List<int> listNew = new List<int>(new []{ 1, 2, 3 }); // Does not require LINQ
Note that LINQ
is available in .NET 3.5
or higher.请注意, LINQ
在.NET 3.5
或更高版本中可用。
More information更多信息
Since arrays already implement IList<T>
in .NET then there's not really any need for an equivalent of Arrays.asList
.由于数组已经在 .NET 中实现了IList<T>
,因此实际上不需要等效的Arrays.asList
。 Just use the array directly, or if you feel the need to be explicit about it:只需直接使用数组,或者如果您觉得需要明确说明它:
IList<int> yourList = (IList<int>)existingIntArray;
IList<int> anotherList = new[] { 1, 2, 3, 4, 5 };
This is about as close as you'll get to the Java original: fixed-size, and writes pass through to the underlying array (although in this case the list and the array are exactly the same object).这与您将获得的 Java 原始版本非常接近:固定大小,并且写入传递到底层数组(尽管在这种情况下,列表和数组是完全相同的对象)。
Further to the comments on Devendra's answer , if you really want to use exactly the same syntax in .NET then it'll look something like this (although it's a pretty pointless exercise, in my opinion).除了对Devendra's answer的评论之外,如果你真的想在 .NET 中使用完全相同的语法,那么它看起来会像这样(尽管在我看来这是一个非常毫无意义的练习)。
IList<int> yourList = Arrays.AsList(existingIntArray);
IList<int> anotherList = Arrays.AsList(1, 2, 3, 4, 5);
// ...
public static class Arrays
{
public static IList<T> AsList<T>(params T[] source)
{
return source;
}
}
not sure whether you want to convert an array to a list as per Devendra's answer or create a new populated list in one go if it's the second then this'll do it:不确定您是要按照 Devendra 的回答将数组转换为列表,还是一次性创建一个新的填充列表(如果是第二个),则可以这样做:
new List<int>(){1, 2, 3, 4, 5};
In fact the braces syntax to populate collections will populate Arrays, dictionaries etc...事实上,填充集合的大括号语法将填充数组、字典等......
The implementation of that static method looks like this.该静态方法的实现如下所示。
public static <T> List<T> asList(T... a) {
return new ArrayList<T>(a);
}
The equivalent for You wold be write same utility class with method asList in C# or use the solution presented by Massif. You 的等价物是使用 C# 中的 asList 方法编写相同的实用程序类,或者使用 Massif 提供的解决方案。
public static class Arrays {
public static List<T> asList<T>(params T[] a)
{
return new List<T>(a);
}
}
要创建单项数组,您只需执行以下操作:
long[] arr = new[] { 1L };
return new List<int> {A,B};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.