Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find a match with 2 comma separated strings with LINQ

Tags:

c#

linq

I am new to LINQ.

I am trying to compare 2 comma separated strings to see if they contain a matching value.

I have a string that contains a list of codes. masterFormList = "AAA,BBB,CCC,FFF,GGG,HHH"

I am trying to compare it to a list of objects. In a given field FormCode contains a comma separated string of codes. I want to see if this at lease one code in this string is in the masterFormList. How would I write linq to accomplish this?

Right now I have:

resultsList = (from r in resultsList
where r.FormCodes.Split(',').Contains(masterFormList)
select r).ToList();

It does not return any matching items from the list.

Please advise

like image 465
John Doe Avatar asked Aug 07 '13 16:08

John Doe


People also ask

How to get comma-separated string in c#?

How to get a comma separated string from an array in C#? We can get a comma-separated string from an array using String. Join() method. In the same way, we can get a comma-separated string from the integer array.

Can you use Linq on a string?

LINQ can be used to query and transform strings and collections of strings. It can be especially useful with semi-structured data in text files. LINQ queries can be combined with traditional string functions and regular expressions. For example, you can use the String.


1 Answers

You'd need to build a collection of the items to search for, then check to see if there are any contained within that set:

var masterSet = new HashSet<string>(masterFormList.Split(','));

resultsList = resultsList
                 .Where(r => r.FormCodes.Split(',')
                              .Any(code => masterSet.Contains(code)))
                 .ToList();
like image 56
Reed Copsey Avatar answered Nov 04 '22 10:11

Reed Copsey