Dynamic linq enums filtering error

c# datagrid dynamic-linq wpf

Question

I trying to use dynamic linq for runtime datagrid filtering with DataGridFiltering project.but i have a problem with enums.

for example, i have a class which contain an enum property 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; }
}

and StudentType enum is :

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

i create a controller class for work with list of students.

in my controller i have a method to find students by type.

this is FindByType Method:

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

when i call FindByType Method i get this error in ParseMemberAccess method of dynamic linq:

Methods on type 'Enum' are not accessible

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

Popular Answer

I think the problem is that the dynamic linq library you are using does not support any Enum methods, such as Enum.Equals(otherVal), or Enum.ToString(). One way to get around this, if you have to use dynamic-linq is :

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

However, if you are able to use standard linq, and you really want to pass in a string for some reason, something like this is much cleaner:

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

Edit : If you need the ability to search using StartsWith and you are not allowed to use the standard linq query above, here is something that will give the same result with alot more code

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