小编Moo*_*thy的帖子

表达式树中没有发生隐式转换

我遇到了一个场景,我需要根据输入对不同属性的自定义类型列表进行排序.在几篇文章的帮助下,我能够使用LINQ.Auring进行单元测试的通用实现,其中一个测试失败,因为当使用Expression树创建lamda表达式时发生了隐式转换.

下面我已经放了示例代码来理解问题(不确定为什么格式化不正确,对不起)

static class ExtensionMethods
{
 public static IEnumerable<TSource> Sort<TSource>(this IEnumerable<TSource> unSortedList, Func<TSource, object> selector, bool isAscending)
    {
       return isAscending ? unSortedList.OrderBy(selector) :                 unSortedList.OrderByDescending(selector);
}   
}

class Program
{

    class Student
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }

    static void Main(string[] args)
    {
        var unOrderedStudents = new List<Student>
                           {
                               new Student{ Name="A", Age=20},
                               new Student{Name = "B", Age=19}
                           };


        //This Works
        var sortUsingLamda = unOrderedStudents.Sort<Student>(stud => stud.Age, true);


        //Exception - Expression …
Run Code Online (Sandbox Code Playgroud)

.net c# linq expression-trees type-parameter

6
推荐指数
1
解决办法
3271
查看次数

标签 统计

.net ×1

c# ×1

expression-trees ×1

linq ×1

type-parameter ×1