1

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

haldo
  • 14,512
  • 5
  • 46
  • 52

2 Answers2

1

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)));
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • Dmitry Bychenko, Can you pls check my post so far I haven't got any answers yet posted on (13/6/2021) if you have any answers for this.... https://stackoverflow.com/questions/67961086/api-abuse-security-vulnerability-issue-mvc-app – Sayeed Ahmed Jun 14 '21 at 14:21
0

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)));
jdweng
  • 33,250
  • 2
  • 15
  • 20
  • Can you pls check my post so far I haven't got any answers yet posted on (13/6/2021) if you have any answers for this.... https://stackoverflow.com/questions/67961086/api-abuse-security-vulnerability-issue-mvc-app – Sayeed Ahmed Jun 14 '21 at 14:21