Search code examples
c#listlinqlistobject

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


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


Solution

  • 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();