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.
5
Answers
You can initialize the list with an empty string variable.
or something live this
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 thisYou 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.
You can write a method that adds your item to two lists:
You can call it via
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:
It allows you to avoid writing
Add
for each list.You can of course do something like this:
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:
Fully working example in dotnet fiddle