How to transfer items of one static list to another - c#

I have two static lists namely list1 and list2
private static IList<String> list1;
private static IList<String> list2;
list1 = new List<String>() { "v1001", "v1002", "v1003","v1004" };
I am trying to transfer items of list1 into list2
list2 = list1;
Now when i try to remove something from list2, that item gets removed from list1 also.
var version = "v1001"
list2.Remove(version);
How can i accomplish this, that i can only remove from list2 without hindering list1.

Both list 2 and list 1 in your exmaple are the same object with variables list2 and list1 pointing at it. You can use
list2 = new List<string>(list1);
which will make them different objects.

You can use the copy constructor:
list2 = new List<string>(list1);
or use Linq:
list2 = list1.Select(s => s).ToList();
which could also be called statically:
list2 = Enumerable<string>.ToList(list1);
NOTE: The other examples are only given for reference - the copy constructor provided in Yuriy's answer is the cleanest way.

The reason that removing from list2 also removes from list1 is that both list1 and list2 are reference types. What I mean by this is that list1 and list2 basically store where your list is somewhere off in memory. When you set list2 to list1 with the = operator what you actually do is tell list2 "alright you're going to point to the same place in memory that list1 is pointing to." This means that if you change something using the reference list1 it will look like this change is duplicated for list2 (but it's actually just changing the same data). To get around this, instead of
list2 = list1;
I think you could use this (as Yuriy Faktorovich said):
Edit: try this
class Program
{
private static IList<string> list1 = new List<string>() { "v1001", "v1002", "v1003", "v1004" };
private static IList<string> list2 = new List<string>(list1);
static void Main(string[] args)
{
list1.Remove("v1001");
print(list1);
print(list2);
}
private static void print(IList<string> list)
{
foreach (string str in list)
{
Console.WriteLine(str);
}
Console.WriteLine();
}
}

Related

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

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

Get unique elements in two lists where items don't match 100% (just partially)

My idea is to use a new list (List1) and compare it with another list (List2) and create a new list (List3) that exclude all common elements in both lists and results on the non common elements. The difficult thing (to me) is that List1 and List2 elements are not a true match. List1 elements might be part of List2 elements, but not a truly match. Using exclude does not seem to allow the use of IndexOf to compare the two list elements.
Does anyone have an idea how to achieve this?
Thanks in advance.
Assuming you have List1 and List2. Below is the simplest way to compare elements in two lists.
IList<string> List3 = new List<string>();
foreach (var item1 in List1)
{
foreach(var item2 in List3)
{
if (item1 == item2)
{
List3.Add(item1);
}
}
}
My idea is to use a new list (List1) and compare it with another list
(List2) and create a new list (List3) that exclude all common elements
in both lists and results on the non common elements.
From Comments
I need to compare each element in both lists List1 element exists in
List2 element (both strings).
One of the easiest ways to find unique from two lists
var List1 = new List<string>() { "a", "b", "c", "d" };
var List2 = new List<string>() { "a", "e", "f", "g", "c","z" };
var List3 = new List<string>();
List3.AddRange(List1.Except(List2));
List3.AddRange(List2.Except(List1));
List3.ForEach(l=>Console.WriteLine(l));
How about this:
List commonElements = new List<string>();
foreach (var smallString in SmallList)
{
if (large.Any(x => x.Contains(smallString)))
{
// Add to common elements
commonElements.Add(smallString);
}
}

Compare the difference between two list<string>

I'am trying to check the difference between two List<string> in c#.
Example:
List<string> FirstList = new List<string>();
List<string> SecondList = new List<string>();
The FirstList is filled with the following values:
FirstList.Add("COM1");
FirstList.Add("COM2");
The SecondList is filled with the following values:
SecondList.Add("COM1");
SecondList.Add("COM2");
SecondList.Add("COM3");
Now I want to check if some values in the SecondList are equal to values in the FirstList.
If there are equal values like: COM1 and COM2, that are in both lists, then filter them from the list, and add the remaining values to another list.
So if I would create a new ThirdList, it will be filled with "COM3" only, because the other values are duplicates.
How can I create such a check?
Try to use Except LINQ extension method, which takes items only from the first list, that are not present in the second. Example is given below:
List<string> ThirdList = SecondList.Except(FirstList).ToList();
You can print the result using the following code:
Console.WriteLine(string.Join(Environment.NewLine, ThirdList));
Or
Debug.WriteLine(string.Join(Environment.NewLine, ThirdList));
Note: Don't forget to include: using System.Diagnostics;
prints:
COM3
You can use Enumerable.Intersect:
var inBoth = FirstList.Intersect(SecondList);
or to detect strings which are only in one of both lists, Enumerable.Except:
var inFirstOnly = FirstList.Except(SecondList);
var inSecondOnly = SecondList.Except(FirstList);
To get your ThirdList:
List<string> ThirdList = inSecondOnly.ToList();
Than for this king of reuqirement you can can make use of Except function.
List<string> newlist = List1.Except(List2).ToList();
or you can do this , so the below one create new list three which contains items that are not common in list1 and list2
var common = List1.Intersect(List2);
var list3 = List1.Except(common ).ToList();
list3.AddRange(List2.Except(common ).ToList());
the above one is help full when list1 and list2 has differenct item like
List<string> list1= new List<string>();
List<string> list2 = new List<string>();
The FirstList is filled with the following values:
list1.Add("COM1");
list1.Add("COM2");
list1.Add("COM4");
The SecondList is filled with the following values:
list2 .Add("COM1");
list2 .Add("COM2");
list2 .Add("COM3");
by using above code list3 contains COM4 and COM3.

check whether a List<string> contains an element in another List<string> using LINQ

How do I check whether a List contains an element that exists in another List using LINQ in C#? I don't want to use a for/while loop.
So, if List1 has A, B, C and List2 has B, 1, 2, then I would return true.
Try this:
List<string> a = ...
List<string> b = ...
var inComon = a.Intersect(b).Any();
Use Enumerable.Any Method:
List<string> l1 = new List<string> { "1", "2" };
List<string> l2 = new List<string> { "1", "3" };
var result = l2.Any(s => l1.Contains(s));
I'd say the Intersect method (see answer by dasblinkenlight) + Any must work better than Contains + Any. It is definetely better to use Any than Count.

How to splice two C# lists into one? Or maybe use a different collection type?

List<string> list1 = new List<string>();
list1.Add("Blah");
list1.Add("Bleh");
list1.Add("Blih");
List<string> list2 = new List<string>();
list2.Add("Ooga");
list2.Add("Booga");
list2.Add("Wooga");
Is there a method to create a third list that has {"Blah", "Bleh", "Blih", "Ooga", "Booga", "Wooga"} or, alternatively, change list1 so it has the three additional elements in list2?
I guess this is the solution:
list1.AddRange(list2)
With LINQ, you can do:
List<string> list1 = new List<string>();
list1.Add("Blah");
list1.Add("Bleh");
list1.Add("Blih");
List<string> list2 = new List<string>();
list2.Add("Ooga");
list2.Add("Booga");
list2.Add("Wooga");
var finalList = list1.Concat( list2 ).ToList();
Take a look at the Union() method of a List.

Categories