0

What is the best code for comparing 2 comma separated strings and retrieving values that intersect? For instance lets say I have string "a,b,c" and the target string "x,b,y", I need result saying there is 1 occurrence.

As suggested here One way of doing this is

public static bool UserCanAccessThisPage(string userAccessGroups,
    string pageItemAccessGroups)
{
    return userAccessGroups.Split(',')
                           .Select(s => s.Trim())
                           .Contains(pageItemAccessGroups);
}

But this will only check the match but I do also need occurrences. Any suggestions please

Community
  • 1
  • 1
Naga
  • 2,368
  • 3
  • 23
  • 33

1 Answers1

2

Use Enumerable.Intersect to get intersection of two sequences:

var occurrences = 
    userAccessGroups.Split(',').Select(s => s.Trim())
         .Intersect(pageItemAccessGroups.Split(',').Select(s => s.Trim()));

Checking if occurrences exist:

bool exist = occurrences.Any();

Getting occurrences count:

int count = occurrences.Count();

To make code more readable you can store groups in local variables:

 // this can be ordinal named method
 Func<string, IEnumerable<string>> parse = 
     csv => csv.Split(',').Select(s => s.Trim());

 var userGroups = parse(userAccessGroups);
 var pateItemGroups = parse(pageItemAccessGroups);
 var occurrences = userGroups.Intersect(pageItemGroups);
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459