Dynamic linq enums filtering error

c# datagrid dynamic-linq wpf

Question

I'm attempting to utilize dynamic linq for Project DataGridFiltering datagrid filtering at runtime. However, I struggle with enums.

I have a class, for instance, that has an enum property that looks like this:

public class Student
{
    public Student(int id,string name,StudentType type)
    {
        Id = id;
        Name = name;
        Type = type;
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public StudentType Type { get; set; }
}

student type enum is:

public enum StudentType : byte
{
    Normal=0,
    Good
};

I design a class called a controller to manage a list of students.

I have a mechanism for finding students by type in my controller.

FindByType Method is as follows:

    public IList<Student> FindByType(string type)
    {
        return _students.AsQueryable().Where("Type.ToString().StartWith(@0)",type).ToList();
    }

The ParseMemberAccess function of dynamic linq throws the following error when I use the FindByType method:

Methods on type 'Enum' are not accessible

1
1
8/25/2013 6:04:32 AM

Popular Answer

The dynamic linq library you are using, which I believe is the issue, does not provide any Enum methods, such as Enum.Equals(otherVal) or Enum.ToString (). If you must use dynamic-linq, one method to avoid this is to:

public IList<Student> FindByType(StudentType type)
{
    return _students.AsQueryable().Where("Type  = (@0)", type).ToList();
}

However, something like this is considerably simpler if you are able to use standard linq and you absolutely want to pass in a string for whatever reason:

public IList<Student> FindByType(string type)
{
    return _students.Where(s => s.Type.ToString().StartsWith(type)).ToList();
}

Edit: Here is something that will provide the same result with a lot more code if you need to be able to search using StartsWith but are not permitted to use the normal linq query above.

public IList<Student> FindByType(string type)
{
    //Replace e.StartsWith with whatever method you wish to filter by
    var studentTypeNames =typeof(StudentType).GetEnumNames().Where(e => e.StartsWith(type)).ToList();
    var students = new List<Student>();
    foreach (var studentTypeName in studentTypeNames)
    {
        StudentType studentType;
        Enum.TryParse(studentTypeName, true, out studentType);
        students.AddRange(_students.AsQueryable().Where("Type  = (@0)", studentType).ToList());
    }
    return students;
}
0
8/26/2013 11:23:07 AM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow