假设我有这段代码。
int count = 0;
int id = GetFirstId();
count = getCountById(id);
if(count == 0){
id = GetSecondId();
count = getCountById(id);
if(count == 0){
id = GetThirdId();
count = getCountById(id);
}
}
有没有更好的方法来做到这一点。内部的LOOP和CASE声明更好吗?
答案 0 :(得分:4)
如果您有不同的方法,可以列出方法,然后使用LINQ获得第一个非零count
。如果GetXXXId
的全部具有相同的签名,则会有效。
var idGetters = new Func<int>[]
{
GetFirstId,
GetSecondId,
GetThirdId
// and so on
};
var count = idGetters
.Select(x => x())
.Select(GetCountById)
.SkipWhile(x => x == 0)
.FirstOrDefault();