简体   繁体   English

如何在忽略大小写 c# 的情况下检查枚举值中的“包含”?

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

I need to check string values present in Enum or not using Contains .我需要检查 Enum 中存在的字符串值或不使用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 } .如果给出“星期三”的意思,我需要一个 dayList 结果为{ Id = 3, Name = Wednesday }

If given filter as "Wednesday" means, I need a dayList result as { Id = 3, Name = Wednesday } .如果给定过滤器为“星期三”意味着,我需要一个 dayList 结果为{ Id = 3, Name = Wednesday }

If given filter as "wednesday" means, I need a dayList result as { Id = 3, Name = Wednesday } .如果给定过滤器为“星期三”的意思,我需要一个 dayList 结果为{ Id = 3, Name = Wednesday }

If given filter as "dnes" means, I need a dayList result as { Id = 3, Name = Wednesday } .如果给定过滤器为“dnes”的意思,我需要一个 dayList 结果为{ Id = 3, Name = Wednesday }

If given filter as "xyx" means, the dayList count should be zero.如果给定过滤器为“xyx”,则dayList计数应为零。

You can use a Where clause such as:您可以使用Where子句,例如:

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

where ContainsCaseInsensitive is an extension method on string:其中ContainsCaseInsensitive是字符串的扩展方法:

// 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).您可以稍微重写您的Linq方法链,select 来自Enum值数组的字符串值,并检查Enum名称是否包含过滤器(不区分大小写)。 Then select a ResultObj and convert Enum value back然后 select 一个ResultObj并将Enum值转换回来

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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