5

我现在有以下内容:

switch (Mysort)
{
    case "reqDate":
        lstDMV.Sort((x, y) => DateTime.Compare(x.RequestDate, y.RequestDate));
        break;
    case "notifDate":
        lstDMV.Sort((x, y) => DateTime.Compare(x.NotifDate, y.NotifDate));
        break;
    case "dueDate":
        lstDMV.Sort((x, y) => String.Compare(x.TargetDateShort, y.TargetDateShort));
        break;
    case "days":
        lstDMV.Sort((x, y) => x.DaysLapsed.CompareTo(y.DaysLapsed));
        break;
}

我想摆脱 case 语句,只做类似的事情:

lstDMV.Sort((x, y) => String.Compare(x.MySort, y.MySort));

case 语句非常庞大,它确实会降低可读性。但因为MySort不包含在lstDMV它不工作。有没有其他方法可以代替它?

我当然会更改文本以确保MySort变量值与lstDMV属性名称完全匹配。

我也试过以下没有运气:(

 if (sort != "")
            {
                string xsort, ysort;
                xsort = "x." + sort;
                ysort = "y." + sort;

                lstDMV.Sort((x, y) => String.Compare(xsort, ysort));
            }
4

5 回答 5

2

那么你可以使用反射,假设你所有的属性类型都实现了IComparable

private class Test
{
    public DateTime RequestDate { get; set; }

    public string Name { get; set; }
}

private static void Main(string[] args)
{
    var list = new List<Test>
    {
        new Test
        {
            RequestDate = new DateTime(2012, 1, 1),
            Name = "test"
        },
        new Test
        {
            RequestDate = new DateTime(2013, 1, 1),
            Name = "a_test"
        },
    };

    string mySort = "RequestDate";
    list.Sort((x, y) =>
        {
            // Gets the property that match the name of the variable
            var prop = typeof(Test).GetProperty(mySort);

            var leftVal = (IComparable)prop.GetValue(x, null);
            var rightVal = (IComparable)prop.GetValue(y, null);

            return leftVal.CompareTo(rightVal);
        });

    Console.Read();
}

我不建议这样做,因为即使代码可能更少,它的可读性也比switch您当前拥有的要少。

于 2013-01-18T16:35:30.590 回答
2

带有比较器 Func 的字典

    public class YourDataClass {
        public string RequestDate { get; set; }
        public string NotifDate { get; set; }
        .
        .
        .
    }

    public class Sorter<T> where T : YourDataClass {
        private Dictionary<string, Func<T, T, int>> actions =
            new Dictionary<string, Func<T, T, int>> {
                {"reqDate", (x, y) => String.Compare(x.RequestDate, y.RequestDate)},
                {"notifDate", (x, y) => String.Compare(x.NotifDate, y.NotifDate)}
            };

        public IEnumerable<T> Sort(IEnumerable<T> list, string howTo) {
            var items = list.ToArray();
            Array.Sort(items, (x, y) => actions[howTo](x, y));
            return items;
        }
    }

    public void Sample() {
        var list = new List<YourDataClass>();
        var sorter = new Sorter<YourDataClass>();
        var sortedItems = sorter.Sort(list, "reqDate");
    }
于 2013-01-18T16:38:13.870 回答
1

Linq 和 Reflection 的结合,用 3 行代码解决您的问题。这是概念证明:

public class Test
{
    public string Name;
    public int Age;
    public DateTime Since;
}

void Main()
{
    var tests = new Test[] {
        new Test(){Name="Dude", Age=23, Since = new DateTime(2000,2,3)},
        new Test(){Name="Guy", Age=29, Since = new DateTime(1999,3,4)},
        new Test(){Name="Man", Age=34, Since = new DateTime(2008,11,5)},
        new Test(){Name="Gentleman", Age=40, Since = new DateTime(2006,7,6)}
    };

    //up until here, all code was just test preparation. 
    //Here's the actual problem solving:

    string fieldToOrderBy = "Since"; //just replace this to change order
    FieldInfo myf = typeof(Test).GetField(fieldToOrderBy);
    tests.OrderBy(t=>myf.GetValue(t)).Dump(); 

    //the Dump() is because I ran this in LinqPad. 
    //Replace it by your favaorite way of inspecting an IEnumerable
}

请注意,字段信息是在排序之前获取的,以尝试提高性能。

我知道您的“SortBy”字符串不是字段名称,但这是问题的简单部分,您可以通过使用字典将 SortBy 字符串映射到 FieldName 来解决。

于 2013-01-18T16:35:41.123 回答
0

假设您的xandy属于 type A,您可以将映射存储在字典中:

var sortingFuncs = new Dictionary<string, Func<A, A, int>>();

排序方法的调用将不再需要switch

lstDMV.Sort(sortingFuncs[Mysort]);

但是请注意,您最终会在其他地方得到几乎一样多的代码,因为必须在某个时候填充字典。一个优点是这个过程可以更加动态,例如,您可以让插件添加自己的排序键以及比较功能。

另一方面,可能会有非常轻微的性能损失,因为编译器不可能再根据符合条件的值优化选择代码Mysort

于 2013-01-18T16:38:01.623 回答
0

创建属性选择器:

Func<T, object> CreatePropSelector<T>(string propertyName)
{
    var parameter = Expression.Parameter(typeof(T));
    var body = Expression.Convert(Expression.PropertyOrField(parameter, propertyName), typeof(object));
    return Expression.Lambda<Func<T, object>>(body, parameter).Compile();
}

并使用它按属性名称排序序列:

lstDMV.OrderBy(CreatePropSelector<YourObjectType>(Mysort))

与其他 Linq 方法一样,它不会对列表进行排序,但会创建枚举器:

Mysort = "RequestDate";
foreach(var item in lstDMV.OrderBy(CreatePropSelector<YourObjectType>(Mysort)))
     // sequence ordered by RequestDate property
于 2013-01-18T16:40:17.590 回答