我的方法应该检查我传递的int数组是否有任何负值,如果是,它应该将它们保存到一个字符串中并返回每个与它们所在的索引一起。现在,该方法仅返回数组的第一个负值。如何将每个负值及其索引添加到字符串中?
public static string FindNegative(int[] array)
{
string yes = null;
foreach (var n in array)
{
if (n < 0)
{
yes += (Array.IndexOf(array, n) + ":" + n + ",");
}
return yes;
}
return null;
}
答案 0 :(得分:1)
.bouncyHouse {
height:200px;
width:150%;
background-color: black;
position: relative;
}
.bouncer {
position: absolute;
width: 200px;
color:white;
font-size:50px;
background-color:yellow;
}
.bouncer:nth-child(2){
top: 30px;
left: 100px;
background-color:green;
}
.bouncer:nth-child(3){
top: 50px;
left: 200px;
background-color:red;
}
虽然,这也可行:
public static string FindNegative(int[] array)
{
string yes = null;
foreach (var n in array)
{
if (n < 0)
{
yes += (Array.IndexOf(array, n) + ":" + n + ",");
}
}
return yes;
}
但是,我建议这样做:
public static string FindNegative(int[] array)
{
return String.Join(",",array.Where(x=>x<0)
.Select((e,i)=>String.Format("{0}:{1}",i,e)));
}
答案 1 :(得分:1)
这是因为你从循环内部返回,更改代码如下&amp;最后返回。
public class FindNegativeResult {
public int Index {get;set;}
public int Number {get;set;}
}
public static IEnumerable<FindNegativeResult> FindNegative(int[] array)
{
return array.Where(x=>x<0)
.Select((e,i)=>new FindNegativeResult {Index=i, Number=e});
}
答案 2 :(得分:1)
更改您的代码如下:
public static string FindNegative(int[] array)
{
string yes = null;
foreach (var n in array)
{
if (n < 0)
{
yes += (Array.IndexOf(array, n) + ":" + n + ",");
}
}
return yes;
}
答案 3 :(得分:1)
public static string FindNegative(int[] array)
{
string yes = String.Empty;
foreach (var n in array)
if (n < 0)
yes += (Array.IndexOf(array, n) + ":" + n + ",");
return yes;
}