Home > OS >  How can I add the same value into multiple lists in one line?
How can I add the same value into multiple lists in one line?

Time:09-22

I have two lists, l1 & l2

List<string> l1 = new List<string>();
List<string> l2 = new List<string>();

I want to put string.Empty into both of them in a single go.

We can do for variables like -

string a;
string b;
a = b = string.Empty;

I don't want to create List<List<string>>

Can anyone help me with it? thanks in advance.

CodePudding user response:

I want to put string.Empty into both of them in a single go.

You cannot. You could make them point to the same list, but you cannot add into both lists at the same time. There also is no point to it. You don't gain anything. If you need this for anything but code aesthetics, please open a question containing your reasons to do this, because there is different concepts depending on what you want to achieve with it.

CodePudding user response:

You can initialize the list with an empty string variable.

List<string> l1 = new List<string>() { string.Empty };

or something live this

string[] array = { string.Empty };
List<string> l1 = new List<string>(array);
List<string> l2 = new List<string>(array);

Either way, you will have same or less number of lines of code as you have now.

doing l1 = l2 will not work for Lists but you can do something like this

List<string> l2 = l1.ToList();

CodePudding user response:

You can write a method that adds your item to two lists:

private void AddToTwoLists<T>(List<T> list1, List<T> list2, T item)
{
    list1.Add(item);
    list2.Add(item);
}

You can call it via

AddToTwoLists(l1, l2, string.Empty);

CodePudding user response:

I don't want to create List<List<string>>

If you have only two lists you could do it without a two-dimensional array, but if you plan to have more of them at some point it would be a more convenient and scalable solution to use an array:

var l1 = new List<string>();
var l2 = new List<string>();

foreach (var list in new[] { l1, l2 })
   list.Add(string.Empty);

It allows you to avoid writing Add for each list.

CodePudding user response:

You can of course do something like this:

// Most comparable solution to:
string a;
string b;
a = b = string.Empty;

// is in my opinion this
List<string> list1, list2 = new List<string>(list1 = new List<string>{ string.Empty });

But to be honest I don't get your problem why you would do this. This code is just creating two lists with one entry. And at the end it's the same result like:

List<string> list1 = new List<string>{ string.Empty }
List<string> list2 = new List<string>{ string.Empty }

Fully working example in dotnet fiddle

  • Related