DateTime.Compare(x.Req-6ren">
gpt4 book ai didi

c# - 在 x y 排序中使用变量

转载 作者:太空狗 更新时间:2023-10-29 23:16:09 25 4
gpt4 key购买 nike

我现在有以下内容:

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));
}

最佳答案

带有比较器 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");
}

关于c# - 在 x y 排序中使用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14402930/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com