Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 491 Vote(s) - 3.47 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Shortcut for creating single item list in C#

#1
In C#, is there an inline shortcut to instantiate a List<T> with only one item.

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

#2
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", ... };
Reply

#3
You can also do

new List<string>() { "string here" };

Reply

#4
I would just do

var list = new List<string> { "hello" };
Reply

#5
A different answer to my earlier one, based on exposure to the [Google Java Collections][1]:

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


[1]:

[To see links please register here]

Reply

#6
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.
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through