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
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With