Arrays.asList( ... ) in .Net

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.

More information

  • Enumerable.ToList Method
  • C# ToList Extension Method

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

Tags:

.Net

Java