简体   繁体   中英

Arrays.asList( ... ) in .Net

I am looking for the simplest way to write the following Java code

Arrays.asList(1L);

in .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.

Since arrays already implement IList<T> in .NET then there's not really any need for an equivalent of 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).

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).

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:

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.

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};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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