Jame
Jame

Reputation: 22190

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

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

Upvotes: 10

Views: 9367

Answers (3)

Robert MacLean
Robert MacLean

Reputation: 39261

You can use the Intersect extension method. To do it case insenstive you can use an equaty comparer:

class Program
{
    static void Main(string[] args)
    {

        List<string> lst1 = new List<string>();
        List<string> lst2 = new List<string>();

        CaseInsensitiveEquityComparer comparer = new CaseInsensitiveEquityComparer();

        var result = lst1.Intersect(lst2, comparer);

    }
}

class CaseInsensitiveEquityComparer : IEqualityComparer<string>
{

    public bool Equals(string x, string y)
    {
        return String.Compare(x,y,true,CultureInfo.CurrentCulture) == 0;
    }

    public int GetHashCode(string obj)
    {
        return obj.GetHashCode();
    }
}

Upvotes: 1

Dyppl
Dyppl

Reputation: 12381

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

Upvotes: 24

rkg
rkg

Reputation: 5719

You can use the Enumerable.Intersect method

Refer to the MSDN documentation for examples: http://msdn.microsoft.com/en-us/library/bb460136.aspx

Refer to Dyppl's answer for implementing the Case insensitive comparison.

Upvotes: 2

Related Questions