how to check list object of element contains a string from the array string in C#

78 views Asked by At

How to check list object value contains any word of string array. its working for "urgent" word but if it comes with "urgent abc" then it fails. Fields is list object.

 public class Fields
    {
        public int _id { get; set; }
        public string Name { get; set; }
        public string Value { get; set; }
    }
 public static string[] urgentWords = {"Urgent","ASAP", "Fast", "Immediately" };
 var UrgentText = data.Fields.Where(x => x.Name.ToLower() == "urgent" && urgentWords.Contains(x.Value, StringComparer.InvariantCultureIgnoreCase)).Count();

sample data of x.Value - "Urgent ABC XYZ" //it should match and UrgentText should give 1 sample data of x.value - "review ASAP" it should match but we are getting 0 results, as it does not contain ABC XYZ

2

There are 2 answers

0
Dmitry Bychenko On BEST ANSWER

Your current code doesn't compile; assuming that you have a collection (array, list) or enumeration of Field

IEnumerable<Field> data = ...

and you want to keep items that such that they contain word from urgentWords within Value property you can combine Linq and Regular Expressions:

First, let's define word as

Non empty sequence of Unicode letters which is not part of another word.

In this case we can use \p{L}+ regular expression.

Second, let's have a HashSet<string> for urgentWords which is more convenient:

private static readonly HashSet<string> urgentWords = new (StringComparer.OrdinalIgnoreCase)
{
    "Urgent", "ASAP", "Fast", "Immediately"
};

Then the query can be

using System.Linq;
using System.Text.RegularExpressions;

...

var result = data
  .Where(item => "urgent".Equals(item.Name, StringComparison.OrdinalIgnoreCase))
  .Where(item => Regex
     .Matches(item.Value, @"\p{L}+")
     .Cast<Match>()
     .Any(match => urgentWords.Contains(match.Value)))
  .ToArray();
0
Denis Micheal On

This

var UrgentText = data.Fields.Where(x => x.Name.ToLower() == "urgent" && urgentWords.Contains(x.Value, StringComparer.InvariantCultureIgnoreCase)).Count();

is evaluating to

Pick anything in data where x.Name equals "urgent" and urgentWords array contains x.value.

data of x.value - "review ASAP" it should match but we are getting 0 results, as it does not contain ABC XYZ

What is the x.name for "review ASAP" ,if it isn't equal to "urgent" then that condition will always evaluate to false.

So either change to only check if urgentWords array contains string

var UrgentText = data.Fields.Where(urgentWords.Contains(x.Value, StringComparer.InvariantCultureIgnoreCase)).Count();

or change condition from && to ||

var UrgentText = data.Fields.Where(x => x.Name.ToLower() == "urgent" || urgentWords.Contains(x.Value, StringComparer.InvariantCultureIgnoreCase)).Count();