Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.net(C#) Comparing two list of strings and removing non matching elements

Tags:

c#

Is there any way to compare two list of strings(regardless of case sensitivity) or do I need to write custom code for such comparison? I also want to remove non-matching items from my dictionary.

e.g

List<string> lst1 = new List<string>();
lst1.Add("value1");
lst1.Add("VALUE2");

List<string> lst2 = new List<string>();
lst2.Add("value1");
lst2.Add("value2");
lst2.Add("value3");

Now after comparison I want to have only "value1" and "value2" in lst2.

Regards, JS

like image 423
Jame Avatar asked Mar 17 '11 05:03

Jame


1 Answers

You can use LINQ Intersect method.

var result = lst1.Intersect(lst2, StringComparer.InvariantCultureIgnoreCase);

You can avoid creating your own implementation of IEqualityComparer<string> by using StringComparer

If you want the result to be in the lst2, then do it like that:

lst2 = lst1.Intersect(lst2, StringComparer.InvariantCultureIgnoreCase).ToList();
like image 73
Dyppl Avatar answered Oct 16 '22 11:10

Dyppl