c# - Turning a read in list into a 2D array for manipulation -
i have file have read c# console app contains information such this:
player;team;pos;hr;rbi;avg abreu, j;cws;1b;30;101;0.29 altuve, j;hou;2b;15;66;0.313 andrus, e;tex;ss;7;62;0.258
i have sort 143 items on list rbi column, descending. i'm have go 2d array, since class has not yet gotten lists or datatables or of sort.
since professor of class likes use methods whenever possible, far have this:
public static string[] openlist() { string[] playerfile = file.readalllines("players.txt"); return playerfile; } public static string[] splitlist() { foreach (string playerinfo in openlist()) { string[] playerstuff = playerinfo.split(';'); foreach (string player in playerstuff) { console.write(player + '\t'); //string individualplayer = player + '\t'; } console.writeline(); } }
i know printing @ point not needs done, give me complete list, in original order.
i suppose question this: since have list imported , split, how go setting 2d array can manipulate? know how work them if i'm hardcoding them in. guess i'm missing obvious here. pointer in right direction nice.
thanks.
as direct answer question, can create 2d array this:
string[] entries = openlist(); string[,] array_2d = new string[entries.length, 6]; for(int = 0 ; < entries.length ; i++) { string[] parts = entries[i].split(';'); (int j = 0; j < 6; j++) { array_2d[i, j] = parts[j]; } } //use array_2d here
however, better way go create class represents entry in file. example:
public class entry { public string player {get;set;} public string team {get;set;} public string pos {get;set;} public int hr {get;set;} public int rbi {get;set;} public double avg {get;set;} }
and can create method (e.g. createentry
) takes in line , parses , returns entry
object.
the createentry
method this:
public entry createentry(string line) { string[] parts = line.split(); return new entry() { player = parts[0], team = parts[1], pos = parts[2], hr = convert.toint32(parts[3]), rbi = convert.toint32(parts[4]), avg = convert.todouble(parts[5]) }; }
then able create list<entry>
contains list of entries form file , can work them like. example:
var entries = openlist() .select(x => createentry(x)) .tolist(); var sorted_entries = entries .orderbydescending(x => x.rbi) .tolist();
Comments
Post a Comment