使用xy排序中的变量

Mad*_* Zu 5 .net c# asp.net

我现在有以下内容:

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;
}
Run Code Online (Sandbox Code Playgroud)

我想摆脱案例陈述,只做以下事情:

lstDMV.Sort((x, y) => String.Compare(x.MySort, y.MySort));
Run Code Online (Sandbox Code Playgroud)

案例陈述是巨大的,它将真正削减可读性.但因为MySort它没有包含在lstDMV它不起作用.还有其他方法可以替代吗?

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

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

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

                lstDMV.Sort((x, y) => String.Compare(xsort, ysort));
            }
Run Code Online (Sandbox Code Playgroud)

lbo*_*zen 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");
    }
Run Code Online (Sandbox Code Playgroud)