如何重构下面的C#代码
foreach (var pref in ps._prefs) {
for (int i = pref.Value.Count - 1; i >= 0; i--) {
var val = pref.Value[i];
// validate the field presence
try {
// this evaluates the relevent field, to make sure it is still presence.
var prefCode = val.PreferenceCode;
} catch (Exception e) {
Log.Warn(LogType.DataLayerService,
$"Referred field is no longer valid for FieldChooser for preference set. {ps.GetDisplayName()}. Still proceeding to delete the Preference Set.",
HttpContext.Current);
pref.Value.RemoveAt(i);
}
}
}
我尝试过:
ps._prefs.Values.ForEach(list => list.RemoveAll(p => p?.PreferenceCode is null));
答案 0 :(得分:0)
也许它可以根据需要工作。
ps._prefs.ForEach(pref => pref.Value.ForEach(val =>
try {
// this evaluates the relevent field, to make sure it is still presence.
var prefCode = val.PreferenceCode;
} catch (Exception e) {
Log.Warn(LogType.DataLayerService,
$"Referred field is no longer valid for FieldChooser for preference set. {ps.GetDisplayName()}. Still proceeding to delete the Preference Set.",
HttpContext.Current);
pref.Value.Remove(val);
}
));
答案 1 :(得分:0)
我能得到的最接近的是
void Main()
{
List<Test> prefs = new List<Test>(){ new Test (), new Test(){PreferenceCode = 1 }};
var res = prefs.Select(x => {
if (x?.PreferenceCode == null)
Debug.Write(x);
return x;
}).Where(x => x?.PreferenceCode != null);
res.Dump();
}
public class Test {
public inb? PreferenceCode {get; set;}
}
使用RemoveAll
var res2 = prefs.RemoveAll(x => {
if (x?.PreferenceCode == null){
Debug.Write(x);
return true;
}
return false;
});
res2.Dump();
答案 2 :(得分:0)
尝试这样。。不是很确定它是否正常工作!!
foreach(var item in ps._prefs.Values)
item.RemoveAll(i => i.Preference Code is null);
答案 3 :(得分:-2)
尝试以下LINQ:
ps._prefs.ForEach(perf => perf.Value = perf.Value.Where(v => v.PreferenceCode != null).ToList()))
在这里,我为Value
的{{1}}字段分配了一个过滤列表,其中perf
不为空。