gpt4 book ai didi

c# - 将 if-chain 转换为基于规则的字典

转载 作者:行者123 更新时间:2023-11-30 19:24:26 26 4
gpt4 key购买 nike

我无法将巨大的 if 链转换为字典。在遗留解决方案中,Excel 导出是这样完成的:

foreach (DataRow dr in fullData.Rows)
{
DataRow newRow = dt.NewRow();

foreach (DataColumn dc in dt.Columns)
{
String s = dc.Caption;

if (s.Equals("ID"))
newRow[dc] = dr["id"];
else if (s.Equals("PQ-Nr"))
newRow[dc] = dr["pqNummer"];
else if (s.Equals("GJ"))
newRow[dc] = dr["geschaeftsjahr"];
else if (s.Equals("Link"))
newRow[dc] = dr["link"];
/*more complex example*/
else if(s.Equals("GF"))
{
string content = "";
int intVal = 0;
if (Int32.TryParse(dr["id"].ToString(), out intVal))
{
List<Freigabe> liste = DBHelper.getFreigabenByPersonalTyp(intVal, Personal.GF);
foreach (Freigabe f in liste)
{
//build content string here
}
}
newRow[dc] = content.TrimEnd();
}
/*plus around 60 more else if statements*/
}
dt.Rows.Add(newRow);
}
return dt;

我的想法是将规则和分配的实际行分成两部分。所以我创建了一个字典:

var rules = new Dictionary<Func<string, bool>, Func<DataRow, object>>()
{
{y => y == "ID", x => x["id"] },
{y => y == "PQ-Nr", x => x["pqNummer"] },
//....
};

为了获取当前列值,我执行以下操作:

foreach (DataRow dr in fullData.Rows)
{
DataRow newRow = dt.NewRow();

foreach (DataColumn dc in dt.Columns)
{
String s = dc.Caption;

newRow[dc] = from r in rules
where r.Key(s)
select r.Value(dr);
}
dt.Rows.Add(newRow);
}
return dt;

完成的报告中每个单元格的内容现在是:System.Linq.Enumerable+WhereSelectEnumerableIterator2[System.Collections.Generic.KeyValuePair2[System.Func 2[System.String,System.Boolean],System.Func2[System.Data.DataRow,System.Object]],System.Object] 而不是它的值。

我到底做错了什么?

最佳答案

我建议更改 rules输入:

// No lambdas, just string to string
Dictionary<String, String> rules = new Dictionary<String, String>() {
{"ID", "id"},
{"PQ-Nr", "pqNumme"},
{"GJ", "geschaeftsjahr"},
{"Link", "link"},
//TODO: put other rules here
};

等等

foreach (DataRow dr in fullData.Rows) {
DataRow newRow = dt.NewRow();

foreach (DataColumn dc in dt.Columns)
newRow[dc] = dr[rules[dc.Caption]];

dt.Rows.Add(newRow);
}

编辑:在一些复杂规则的情况下(例如"GF"编辑问题中的一个)Dictionary<String, String> rule也可以帮忙:

   foreach (DataColumn dc in dt.Columns) {
String rule;

if (rules.TryGetValue(dc.Caption, out rule))
newRow[dc] = dr[rule]; // <- all the simple rules
else if (dc.Caption.Equals("GF")) { // <- few specific rules
...
}
}

关于c# - 将 if-chain 转换为基于规则的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36932333/

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