Compare the difference between two list<string> - c#

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.

Related

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);
}
}

How to transfer items of one static list to another

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

How to create a list of differences based on two other lists and include duplicates

I have two lists
List<string> list1 as new List<string>();
and
List<string> list2 as new List<string>();
What I want to do is create a third list that is a list of differences.
Example:
list1 contains (Test1, Test2, Test3, Test4)
list2 contains (Test1, Test3)
I would want my new list to contain (Test 2, Test4)
I tried using
newlist = list1.Except(list2).ToList();
and for the above example it works fine.
Example 2:
list 1 contains (Test1, Test1, Test2, Test2)
list 2 is empty
I want my newlist to contain everything (Test1, Test1, Test2, Test2)
If I use the same Except method I was using above I get in my newlist (Test1, Test2)
Is there a way I can include the duplicates?
One more final example so it is hopefully clear on what I am looking for
list1 contains (Test1, Test2, Test2, Test3, Test4)
list2 contains (Test1, Test2, Test5, Test6)
I would want my newlist to contain (Test2, Test3, Test4, Test5, Test6)
One more thing is that list1 and list2 are in no particular order and newlist does not need to be in any particular order either.
I think getting what you are looking for here is going to be really hard to do with an out of the box. Really what you need to do is "summarize" both lists something like a count of each item, then from there, do a different on items, THEN a difference on counts.
You'll have to write this one yourself. The way Except probably works is by putting all of the elements from the first collection into the equivalent of aHashSet<T> and removing every item that's in the second.
What I'd do is something similar: put everything from the first collection into aDictionary<T, int> with values corresponding to occurrence counts. Enumerating over the second collection, subtract from these counts. Then reconstruct a list from the updated counts after subtraction.
Does that make sense?
UPDATE: I have compressed my previous code into something a little smaller:
var list1 = new List<string>() { "Test1", "Test2", "Test2", "Test3", "Test4" };
var list2 = new List<string>() { "Test1", "Test2", "Test5", "Test6" };
var newlist = new List<string>();
list1.ForEach(delegate(string s) { if (!list2.Remove(s)) newlist.Add(s); });
newlist = newlist.Concat(list2).ToList();

Finding whether an element available in GenericList

I have a string[] which contains value {"data1","data2","data3"}.
and i have a GenericList which contains
data2
data4
two records
i want to get the common datas which is avail in string[] and the genericList
Have you tried something like
string[] s = {"data1", "data2", "data3"};
List<string> list = new List<string> { "data2", "data3" };
var commonList = list.Intersect(s);
Have a look at Enumerable.Intersect Method (IEnumerable, IEnumerable)
Assuming it's a List<string> and you're using .NET 3.5 or higher, you can use the Intersect method from LINQ to Objects:
var intersection = stringArray.Intersect(stringList);
Note that this will return a lazily-evaluated IEnumerable<string>. If you need it in an array or a list, call the relevant method:
var intersectionArray = stringArray.Intersect(stringList).ToArray();
// or
var intersectionList = stringArray.Intersect(stringList).ToList();
Also note that this is a set operation - so the result will not contain any duplicates, even if there is duplication of a particular element in both the original collections.
Take a look at the Intersect extension method here
string[] c1 = { "data1", "data2", "data3" };
string[] c2 = { "data2", "data4" };
IEnumerable<string> both = c1.Intersect(c2);
foreach (string s in both) Console.WriteLine(s);
Will print data2.

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