我有一个文件,我已经读入C#控制台应用程序,其中包含以下信息:
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
我现在必须通过RBI列对此列表中的所有143个项目进行排序。 我非常肯定我必须使用2D数组,因为这个类还没有进入Lists或DataTables或类似的东西。
由于这个班级的教授喜欢我们尽可能使用方法,所以我到目前为止:
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();
}
}
我知道此时打印它不是需要做的事情,只会按照原始顺序给我一个完整的列表。
我想我的问题是这样的:因为我现在已经导入并拆分了这个列表,我该如何设置它作为2D数组然后我可以操作?如果我对它们进行硬编码,我知道如何使用它们。 我想我只是遗漏了一些明显的东西。正确方向的指针会很好。
感谢。
答案 0 :(得分:1)
作为您问题的直接答案,您可以像这样创建2D数组:
string[] entries = openList();
string[,] array_2d = new string[entries.Length, 6];
for(int i = 0 ; i < entries.Length ; i++)
{
string[] parts = entries[i].Split(';');
for (int j = 0; j < 6; j++)
{
array_2d[i, j] = parts[j];
}
}
//Use array_2d here
但是,更好的方法是创建一个表示文件中条目的类。例如:
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;}
}
然后你可以创建一个方法(例如CreateEntry
),它接受一行并解析它并返回一个Entry
对象。
CreateEntry
方法看起来像这样:
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])
};
}
然后,您将能够创建一个包含文件条目列表的List<Entry>
,然后您可以根据需要使用它们。例如:
var entries =
openList()
.Select(x => CreateEntry(x))
.ToList();
var sorted_entries =
entries
.OrderByDescending(x => x.RBI)
.ToList();
答案 1 :(得分:0)
试试这个
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static List<Player> players = new List<Player>();
const string FILENAME = @"c:\temp\test.txt";
static void Main(string[] args)
{
StreamReader reader = new StreamReader(FILENAME);
string inputLine = "";
int lineCount = 0;
while ((inputLine = reader.ReadLine()) != null)
{
lineCount++;
inputLine = inputLine.Trim();
if (inputLine.Length > 0)
{
if (lineCount > 1)
{
string[] playerStuff = inputLine.Split(';');
players.Add(new Player(playerStuff));
}
}
}
reader.Close();
}
}
public class Player
{
public string name { get; set;}
public string team { get; set;}
public string position { get; set;}
public int hr { get; set;}
public int rbi { get; set;}
public double avg { get; set;}
public Player(string[] line)
{
this.name = line[0];
this.team = line[1];
this.position = line[2];
this.hr = int.Parse(line[3]);
this.rbi = int.Parse(line[4]);
this.avg = double.Parse(line[5]);
}
}
}