Reputation: 659
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.
Upvotes: 2
Views: 1918
Reputation: 23228
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();
Upvotes: 0
Reputation: 271420
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;
Upvotes: 5