0

I need to read in an array of baseball player names and various stats that is delimited with a ';'. Here are 2 lines so my example code will make sense

Abreu, J;CWS;1B;30;101;0.29
Altuve, J;HOU;2B;15;66;0.313

Currently I am reading the file into an array where each line is in its own index in the array with the following code:

    public static void fillArray()
    {
        string[] linesInFile = File.ReadAllLines(GlobalVariables.filePath);
        //EACH LINE IS A STRING AT THIS POINT
        foreach (string s in linesInFile)
        {
            string[] items = s.Split(';');
            for (int i = 0; i < items.Length; i++)
            {
                Console.WriteLine(items[i]);
                //Console.WriteLine(items[1]);
            }
        }
    }

The only issue is I'm new to C# and don't know how to access this filled array from a different method so I can sort it and display various info etc.

I've searched all permutations I can think of on google, but I can't find any relevant answers.

Thanks for the help.

2
  • What are each of the stats called? Commented Jan 20, 2016 at 5:50
  • @Enigmativity Player;Team;Position;Home runs;RBI;Batting average Commented Jan 20, 2016 at 5:53

6 Answers 6

1

Simply change the signature of your fillArray method to return your array. Given you sample code, you'll need a two dimensional array, because you have multiple lines so a jagged array would be a good choice if players' stats are not fixed (some players may have fewer or more stats). Alternatively instead of an array you can return a list of lists (List<List<string>>) which are more flexible than arrays. So your code returning a jagged array will look like this:

public static string[][] fillArray()
{
    string[] linesInFile = File.ReadAllLines(GlobalVariables.filePath);
    string[][] result = new string[linesInFile.Length][];
    int index = 0;
    //EACH LINE IS A STRING AT THIS POINT
    foreach (string s in linesInFile)
    {
        string[] items = s.Split(';');
        result[index++] = items;
    }

    return result;
}

Note that it is more preferable/readable to return the array instead of having a global one and change it in your method.

Sign up to request clarification or add additional context in comments.

Comments

1

how to access this filled array from a different method

You would either need to pass the array into the other method as a parameter or you would need to declare the variable outside of the method to up its scope.

Comments

1

One way is by creating a list of those arrays outside of the method fillArray

List<string[]> itemsList = new List<string[]>(); //declare this outside of the method
public static void fillArray()
{
    string[] linesInFile = File.ReadAllLines(GlobalVariables.filePath);
    //EACH LINE IS A STRING AT THIS POINT
    foreach (string s in linesInFile)
    {
        string[] items = s.Split(';');
        itemsList.Add(items); //add the list in the itemsList
        for (int i = 0; i < items.Length; i++)
        {
            Console.WriteLine(items[i]);
            //Console.WriteLine(items[1]);
        }
    }
}

Then simply use it in other method like this:

public void otherMethod(){
    string[] itemsAtZero = itemsList[0]; //your first string[] items
    string[] itemsAtOne = itemsList[1]; //your second string[] items
    //and so on...
}

Comments

1

I would go about it like this:

Player[] players =
(
    from line in File.ReadAllLines(GlobalVariables.filePath)
    let parts = line.Split(';')
    select new Player(
        parts[0], parts[1], parts[2],
        int.Parse(parts[3]), int.Parse(parts[4]),
        double.Parse(parts[5]))
).ToArray();

You'll get this result:

players

You'll need this Player class too:

public sealed class Player : IEquatable<Player>
{
    private readonly string _Name;
    private readonly string _Team;
    private readonly string _Position;
    private readonly int _HomeRuns;
    private readonly int _Rbi;
    private readonly double _BattingAverage;

    public string Name { get { return _Name; } }
    public string Team { get { return _Team; } }
    public string Position { get { return _Position; } }
    public int HomeRuns { get { return _HomeRuns; } }
    public int Rbi { get { return _Rbi; } }
    public double BattingAverage { get { return _BattingAverage; } }

    public Player(string Name, string Team, string Position, int HomeRuns, int Rbi, double BattingAverage)
    {
        _Name = Name;
        _Team = Team;
        _Position = Position;
        _HomeRuns = HomeRuns;
        _Rbi = Rbi;
        _BattingAverage = BattingAverage;
    }

    public override bool Equals(object obj)
    {
        if (obj is Player)
            return Equals((Player)obj);
        return false;
    }

    public bool Equals(Player obj)
    {
        if (obj == null) return false;
        if (!EqualityComparer<string>.Default.Equals(_Name, obj._Name)) return false;
        if (!EqualityComparer<string>.Default.Equals(_Team, obj._Team)) return false;
        if (!EqualityComparer<string>.Default.Equals(_Position, obj._Position)) return false;
        if (!EqualityComparer<int>.Default.Equals(_HomeRuns, obj._HomeRuns)) return false;
        if (!EqualityComparer<int>.Default.Equals(_Rbi, obj._Rbi)) return false;
        if (!EqualityComparer<double>.Default.Equals(_BattingAverage, obj._BattingAverage)) return false;
        return true;
    }

    public override int GetHashCode()
    {
        int hash = 0;
        hash ^= EqualityComparer<string>.Default.GetHashCode(_Name);
        hash ^= EqualityComparer<string>.Default.GetHashCode(_Team);
        hash ^= EqualityComparer<string>.Default.GetHashCode(_Position);
        hash ^= EqualityComparer<int>.Default.GetHashCode(_HomeRuns);
        hash ^= EqualityComparer<int>.Default.GetHashCode(_Rbi);
        hash ^= EqualityComparer<double>.Default.GetHashCode(_BattingAverage);
        return hash;
    }

    public override string ToString()
    {
        return String.Format("{{ Name = {0}, Team = {1}, Position = {2}, HomeRuns = {3}, Rbi = {4}, BattingAverage = {5} }}", _Name, _Team, _Position, _HomeRuns, _Rbi, _BattingAverage);
    }
}

Comments

1

You have to return the array read:

  public static String[][] fillArray() {
    return File
      .ReadLines(GlobalVariables.filePath)
      .Select(line => line.Split(';')) 
      .ToArray(); // usually not necessary, but question requies array 
  }

And so you can, say, print out the array form some other method:

  Console.Write(String.Join(Ebvironment.NewLine, fillArray()
    .OrderBy(items => items[1]) // Let's sort the array by second column
    .ThenBy(items => items[0])  // ..and by 1st column on tie
    .Select(items => String.Join(","))));

A better approach is to return a special designed class Player instead of String[] like this:

  public static Player[] fillArray() {
    return File
      .ReadLines(GlobalVariables.filePath)
      .Select(line => line.Split(';')) 
      .Select(items => new Player(items[0], items[1], items[2]) {
         HomeRuns = Int.Parse(items[3], CultureInfo.InvariantCulture),
         RBI = Double.Parse(items[4], CultureInfo.InvariantCulture),
         Batting = Double.Parse(items[5], CultureInfo.InvariantCulture),
      })
      .ToArray(); // usually not necessary, but question requies array 
  }

and the sample report will be

  Console.Write(String.Join(Ebvironment.NewLine, fillArray()
    .OrderBy(player => player.Team) 
    .ThenBy(player => player.Name)); 

Comments

0

Do something like this... you can find lots of good tutorials online to help you build up your foundation on C#

static void Main()
{
  List<MyObject> myListOfObjects = fillArray();
  DisplaySortedArray(myListOfObjects);
  Console.ReadLine();
}

public static void DisplaySortedArray(List<MyObject> myListOfObjects)
{
  foreach(var myObject in myListOfObjects)
  {
      Console.WriteLine(myObject.Property1);
      Console.WriteLine(myObject.Property2);
      Console.WriteLine(myObject.Property3);
      Console.WriteLine(myObject.Property4);
      Console.WriteLine(myObject.Property5);
      Console.WriteLine(myObject.Property6);
  }
}

public static List<MyObject> fillArray()
{
    string[] linesInFile = File.ReadAllLines(GlobalVariables.filePath);
    List<MyObject> myListOfObjects = new List<MyObject>();

    foreach (string s in linesInFile)
    {
        string[] items = s.Split(';');
        MyObject myObject = new MyObject();
        myObject.Property1 = items[0];
        myObject.Property2 = items[1];
        myObject.Property3 = items[2];
        myObject.Property4 = items[3];
        myObject.Property5 = items[4];
        myObject.Property6 = items[5];
        myListOfObjects.Add(myObject);
    }

    return myListOfObjects;
}

public class MyObject
{
    public string Property1 {get;set;}
    public string Property2 {get;set;}
    public string Property3 {get;set;}
    public string Property4 {get;set;}
    public string Property5 {get;set;}
    public string Property6 {get;set;}
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.