我正在使用 ??
运算符尝试根据在列表中找到的最佳匹配项分配对象。
我有各种匹配规则,但已针对示例进行了简化:
objectImTryingToSet =
MyListOfPotentialMatches.FirstOrDefault(*/lamda checking numerous things*/) ?? //rule1
MyListOfPotentialMatches.FirstOrDefault(*/lamda checking different numerous things*/) ?? //rule2
MyListOfPotentialMatches.FirstOrDefault(*/lamda checking again different numerous things*/); //rule3
出于调试目的,我想存储一个字符串日志记录,哪个规则是成功分配 objectImTryingToSet
的规则,因为我有一个错误,在一个场景中,对象在不应该分配的时候被分配手动筛选所有这些规则以找出错误分配的位置确实令人头疼。
所以我基本上想要,伪:
string ruleThatMatched = null;
objectImTryingToSet =
MyListOfPotentialMatches.FirstOrDefault(*/lamda checking numerous things*/) ?? if (objectImTryingToSet != null) { ruleThatMatched = "rule1" } //rule1
MyListOfPotentialMatches.FirstOrDefault(*/lamda checking different numerous things*/) ?? if (objectImTryingToSet != null) { ruleThatMatched = "rule2" } //rule2
MyListOfPotentialMatches.FirstOrDefault(*/lamda checking again different numerous things*/); if (objectImTryingToSet != null) { ruleThatMatched = "rule3"} //rule3
//tried all the rules and still no match
if (objectImTryingToSet == null)
{
ruleThatMatched = "no rule managed to find a match";
}
这甚至可以使用 ??
运算符吗?
最佳答案
你可以这样做:
var res =
MyListOfPotentialMatches.Select(v => new {r=1, v}).FirstOrDefault(/*lamda checking numerous things*/) ??
MyListOfPotentialMatches.Select(v => new {r=2, v}).FirstOrDefault(/*lamda checking different numerous things*/) ??
MyListOfPotentialMatches.Select(v => new {r=3, v}).FirstOrDefault(/*lamda checking again different numerous things*/);
if (res != null) {
var ruleNumber = res.r;
objectImTryingToSet = res.v;
}
关键是Select
,它将结果与硬编码的规则编号配对。
请注意,您也可以在没有 ??
运算符的情况下执行此操作:
var firstChoice = MyListOfPotentialMatches.Select(v => new {r=1, v}).Where(/*lamda checking numerous things*/);
var secondChoice = MyListOfPotentialMatches.Select(v => new {r=2, v}).Where(/*lamda checking different numerous things*/);
var thirdChoice = MyListOfPotentialMatches.Select(v => new {r=3, v}).Where(/*lamda checking again different numerous things*/);
var res = firstChoice.Concat(secondChoice).Concat(thirdChoice).FirstOrDefault();
if (res != null) {
var ruleNumber = res.r;
objectImTryingToSet = res.v;
}
关于c# - 捕获空合并运算符中的哪个左手项成功分配了变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30940601/