Extract common string from two strings with Comma separated

Viewed 133

I have two strings consisting of several words (Comma separated). If string 1 consisting of words (; separated) which is to be ignored if it presents in string 2, below are the strings

var compToIgnore="Samsung,Motorola,Amazon";
var allCompanies="Godrej,Samsung,Videocon,Huawei,Motorola,Alibaba,Amazon";
var icm = compToIgnore.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
    
foreach (var c in listOfCompanies)
{
    if (c.BrandId.StartsWith("A2"))
    {
        var item = allCompanies.Where(x => !icm.Contains(x));
        var result = string.Join(",", item);
    }
}

In result variable I wanted to have final result as "Godrej,Videocon,Huawei,Alibaba"

I don't see any proper result with above code

2 Answers

You can try Linq in order to query allCompanies:

using System.Linq;

...

var compToIgnore = "Samsung,Motorola,Amazon";
var allCompanies = "Godrej,Samsung,Videocon,Huawei,Motorola,Alibaba,Amazon";

string result = string.Join(",", allCompanies
  .Split(',')
  .Except(compToIgnore.Split(',')));

Note, that Except removes all duplicates. If you want to preserve them, you can use HashSet<string> and Where instead of Except:

HashSet<string> exclude = new HashSet<string>(compToIgnore.Split(','));

string result = string.Join(",", allCompanies
  .Split(',')
  .Where(item => !exclude.Contains(item)));

Try following :

            string compToIgnore = "Samsung,Motorola,Amazon";
            string allCompanies = "Godrej,Samsung,Videocon,Huawei,Motorola,Alibaba,Amazon";
            string[] icm = compToIgnore.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            string[] ac = allCompanies.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

            string results = string.Join(",", ac.Where(x => !icm.Contains(x)));
Related