C # initialization initializer - is it possible to add an element optionally based on a condition?

Now my code is as follows:

var ids = projectId.HasValue ? new List<Guid> { projectId.Value } : new List<Guid>(); 

Is there a more concise way to create a list in one line of code, with one element added additionally ?

+5
source share
5 answers

This is probably not a good idea, but in C # 6, collection initializers also work when Add() is an extension method .

This means that you can write the Add() extension as follows:

 public static void Add<T>(this List<T> list, T? item) where T : struct { if (item.HasValue) { list.Add(item.Value); } } 

And then this code will do what you want:

 var list = new List<Guid> { projectId }; 

Note that this will only work for value types (due to the difference of T / T? ), And there is no easy way to make it work for reference types.

Also, I would find that the line above is very amazing, being shorter is not always better. That is why I will not really use this code.

+1
source

I would solve this using the extension method as follows:

 public static void AddIfNotNull<T>(this List<T> list, T? value) where T : struct { if(value != null) { list.Add(value.Value); } } 

How can it be used as follows:

 var ids = new List<Guid>(); ids.AddIfNotNull(projectId); 

Perhaps not as "cunning" (and not one-line) as your proposal, but, in my opinion, it is much easier to read and understand. If you want to use it as a single line, you could change the type of extension return as a list. This would allow something like var ids = new List<Guid>().AddIfNotNull(projectId);

+2
source

Another idea for the extension method (can the name be improved, perhaps a PossiblyCreateSingletonList ?):

 public static class NullableExtensions { public static List<T> SingletonList<T>(this Nullable<T> item) where T : struct { return item.HasValue ? new List<T> { item.Value } : new List<T>(); } } 

Using:

 Guid? projectId = null; List<Guid> projectIds = projectId.SingletonList(); // empty list 
+2
source

This is pretty concise, but another option is to use LINQ:

 var ids = new[] { projectId }.Where(x => x.HasValue).Select(x => x.Value).ToList(); 
+1
source

If you are going to route the extension method, it should look something like this:

 public static void AddIfNotNull<T>(this List<T> list, T? value) where T : struct { if (value.HasValue) { list.Add(value.Value); } } 

If necessary, you will need to create a second extension method for reference types ( where T : class ).

0
source

Source: https://habr.com/ru/post/1241257/


All Articles