简体   繁体   中英

How to check “Contains” in enum values with ignoring case c#?

I need to check string values present in Enum or not using Contains .

public enum Days
{
    Monday = 1,
    Tuesday = 2,
    Wednesday = 3,
    Thursday = 4,
    Friday = 5,
    Saturday = 6,
    Sunday = 7
}

public class ResultObj
{
   public int Id { get; set; }
   public string Name { get; set; }
}

var filter = "Wed";
var dayList = Enum.GetValues(typeof(Days))
               .Cast<Days>()
               .Where(x => Enum.IsDefined(typeof(Days), filter))
               .Select(d => new ResultObj
               {
                   Id = (int)d,
                   Name = d.ToString()
               }).ToList();

If given "Wed" means, I need a dayList result as { Id = 3, Name = Wednesday } .

If given filter as "Wednesday" means, I need a dayList result as { Id = 3, Name = Wednesday } .

If given filter as "wednesday" means, I need a dayList result as { Id = 3, Name = Wednesday } .

If given filter as "dnes" means, I need a dayList result as { Id = 3, Name = Wednesday } .

If given filter as "xyx" means, the dayList count should be zero.

You can use a Where clause such as:

.Where(x => Enum.GetName(typeof(Days), x).ContainsCaseInsenitive(filter))

where ContainsCaseInsensitive is an extension method on string:

// adapted from: https://stackoverflow.com/a/15464440/5133585
public static bool ContainsCaseInsensitive(this string a, string b) =>
    CultureInfo.InvariantCulture.CompareInfo.IndexOf(a, b, CompareOptions.IgnoreCase) >= 0;

You can rewrite your Linq method chain a little bit, select a string values from array of Enum values and check that Enum name contains the filter (case insensitive). Then select a ResultObj and convert Enum value back

 var filter = "Wed";
 var dayList = Enum.GetValues(typeof(Days))
     .Cast<Days>()
     .Select(x => x.ToString())
     .Where(x => x.Contains(filter, StringComparison.OrdinalIgnoreCase))
     .Select(d => new ResultObj
     {
         Id = (int)Enum.Parse(typeof(Days), d),
         Name = d
     }).ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM