如果在循环后没有匹配项,如何仅获得一个答案 [英] How to get only one answer if there is no match after loop
本文介绍了如果在循环后没有匹配项,如何仅获得一个答案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的代码在数组中有一个for循环,并且具有if语句,如果没有匹配项,我只想得到一个答案.
My code has a for loop in array and has if statement, and I want to get only one answer if there is no match.
for (int i = 0; i < arr.Length; i++)
{
if (arr[i].GetSomeValue() >= 1 && i].GetSomeValue() <= 5)
Console.WriteLine(arr[i]);
else
Console.WriteLine("No data");
}
但是,我得到了这些:
No data
No data
No data
No data
如果没有匹配项,我只需要一个无数据".我尝试添加
I want only one "No data" if there is no match. I tried adding
else break;
}
Console.WriteLine("No data");
但是它不起作用.
我如何得到想要的东西?
How do I get what I want?
推荐答案
基于linq的替代方案:
Alternative based on linq:
using System.Linq;
...
var withinSpecs = arr.Where(e => e.GetSomeValue() >= 1 && e.GetSomeValue() < 5).ToArray();
if(withinSpecs.Length == 0)
{
Console.WriteLine("No data");
}
else
{
foreach(var element in withinSpecs)
Console.WriteLine(element);
}
这篇关于如果在循环后没有匹配项,如何仅获得一个答案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文