我希望划分每个列表的相应值,以便生成一个新列表,其中包含我的两个列表中每个相应索引的划分结果。我的两个列表都是8个值,并且都是int列表。我目前正在创建两个像这样划分的列表:
private void StartSchedule_Click(object sender, EventArgs e)
{
string ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\A2 Computing\C# Programming Project\TriHard.accdb";
string SelectQuery = "SELECT Time.AthleteID, Athlete.AthleteName, Time.EventTime, Event.EventDistance FROM Event INNER JOIN (Athlete INNER JOIN [Time] ON Athlete.[AthleteID] = Time.[AthleteID]) ON Event.[EventID] = Time.[EventID];";
OleDbConnection Connection = new OleDbConnection(ConnectionString);
OleDbCommand Command = new OleDbCommand(SelectQuery, Connection);
Command.Connection.Open();
OleDbDataReader Reader = Command.ExecuteReader(CommandBehavior.CloseConnection);
PaceCalculator pace = new PaceCalculator();
List<int> Distancelist = new List<int>();
List<int> Secondslist = new List<int>();
List<int> Pacelist = new List<int>();
while (Reader.Read())
{
pace = new PaceCalculator();
pace.Distance = (int)Reader["EventDistance"];
int DistanceInt = Convert.ToInt32(pace.Distance);
Distancelist.Add(DistanceInt);
pace = new PaceCalculator();
pace.Time = (string)Reader["EventTime"]; //Reads in EventTime
double Seconds = TimeSpan.Parse(pace.Time).TotalSeconds; //Converts the string into HH:MM:SS as a double
int SecondsInt = Convert.ToInt32(Seconds); //Converts the double into an integer, returning the seconds in the total time
Secondslist.Add(SecondsInt); //Adds the Seconds for each time to the list;
//Need to fix this currently returns just 0
var Pacelist2 = PaceCalc(Distancelist, Secondslist);
listBox3.DisplayMember = "PaceInt";
listBox3.DataSource = (Pacelist2);
}
listBox1.DisplayMember = "DistanceInt";
listBox1.DataSource = Distancelist;
listBox2.DisplayMember = "SecondsInt";
listBox2.DataSource = Secondslist;
这是我正在调用的函数,它试图划分列表,但似乎没有工作:
public List<int> PaceCalc(List<int> Dlist, List<int> Slist)
{
PaceCalculator pace = new PaceCalculator();
List<int> Plist = new List<int>();
pace = new PaceCalculator();
for (int i = 0; i == Dlist.Count; i++)
{
int PaceInt = Dlist[i] / Slist[i];
Plist.Add(PaceInt);
}
return Plist;
}
我希望在listBox3中显示除法的结果。我是否正确划分列表,如何在列表框中显示?
答案 0 :(得分:9)
您的for循环永远不会执行,因为您正在测试i == Dlist.Count
。它应该是:
for (int i = 0;i < Dlist.Count; i++)
或者,您可以使用LINQ执行此操作:
public List<int> PaceCalc(List<int> Dlist, List<int> Slist)
{
return Dlist.Zip(Slist, (a, b) => a / b).ToList();
}
答案 1 :(得分:3)
几个问题:
首先,您需要将for
循环中的检查修改为i < Dlist.Count
。您当前的支票i == Dlist.Count
是错误的。
所以你的方法是:
public List<int> PaceCalc(List<int> Dlist, List<int> Slist)
{
List<int> Plist = new List<int>();
for (int i = 0; i < Dlist.Count; i++)
{
int PaceInt = Dlist[i] / Slist[i];
Plist.Add(PaceInt);
}
return Plist;
}
(我已移除PaceCalculator pace = new PaceCalculator();
,因为您的方法根本不需要它)
二。您不必为DisplayMember
ListBox3
var Pacelist2 = PaceCalc(Distancelist, Secondslist);
listBox3.DataSource = Pacelist2;
虽然,第二个问题不会导致任何错误/异常,因为找不到DisplayMember
,它将使用默认的ToString
重载,您将获得数字