简体   繁体   中英

How to return a string from an int array method in C#

My method is supposed to check to see if the int array I pass through has any negative values, if so it should save them into a string and return each one along with the index they are located at. Right now the method only returns the first negative value of the array. How do I make each negative value and its index get added to a string?

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; 
}
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;
}

Although, this would work too:

public static string FindNegative(int[] array)
{
    return String.Join(",",array.Where(x=>x<0)
      .Select((e,i)=>String.Format("{0}:{1}",i,e)));
}

But, I would recommend this:

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});
}

that is because you are returning from inside the loop, change the code as below & return yes at the end.

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 yes; 
}

Change you code as below:

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)
{
    string yes = String.Empty;

    foreach (var n in array)
        if (n < 0)
            yes += (Array.IndexOf(array, n) + ":" + n + ",");  

    return yes;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM