1

I want to add a range to the list but within the same line as initializing it, I am also just doing a normal add to the list within the same line.

Previously was:

List<Type> dto = new List<Type>();
dto.Add(sequence1);
dto.AddRange(sequence2); //sequence2 is also a list

What I currently have:

List<Type> dto = new List<Type> {sequence1};
dto.AddRange(sequence2);

I want to be able to perform the AddRange in the same line, is this possible?

JayH
  • 194
  • 1
  • 3
  • 17

3 Answers3

4

Have you tried this?

List<Type> dto = new List<Type> (sequence2){sequence1};

It will initialize dto with sequence2 and add sequence1 to the end of collection

Kamil Budziewski
  • 22,699
  • 14
  • 85
  • 105
  • 3
    Just a note, and might not be an issue for JayH, but I think this will reverse the order. In the original code sample, `sequence1` came before the entries in `sequence2`. This line here will have the `sequence2` entries before `sequence1`. – Chris Sinclair Apr 04 '14 at 12:58
  • This didn't work unfortunately, receiving Sequence contains no elements which is odd. Thanks for the suggestion though, sure it will work for some people. – JayH Apr 04 '14 at 13:04
2

You can use LINQ Concat operator on the result of the constructor:

List<int> l1 = new List<int>() { 1, 2 };
List<int> l2 = new List<int>() { 3, 4 };
List<int> r = new List<int>(l1).Concat(l2).ToList();

or if you are just initializing with single element elem, choose one of:

List<int> r = new List<int>() { elem }.Concat(l2).ToList();
List<int> r = new[] { elem }.Concat(l2).ToList();
List<int> r = Enumerable.Repeat(elem, 1).ToList();

Note: depending on the further use of the r, you can skip ToList() because IEnumerable might be enough.

Konrad Kokosa
  • 16,563
  • 2
  • 36
  • 58
0

If it is really important then you could create a extension, which will make it fluent, but how come you only want it in a single line?

class Program
{
    static void Main(string[] args)
    {
        List<int> l1 = new List<int>() { 3, 4 };
        List<int> l2 = new List<int>() { 5, 6 };

        var a = new List<int>() { 1, 2 }.FluentAddRange(l1).FluentAddRange(l2);
    }

}
public static class Extensions
{
    public static List<T> FluentAddRange<T>(this List<T> list, List<T> newList)
    {
        list.AddRange(newList);

        return list;
    }
}
TryingToImprove
  • 7,047
  • 4
  • 30
  • 39