我想知道如何在使用数组的文本文件感兴趣之后找到金额中的前3个事务。基本上,当应用程序打开时,它会在列表框或列表视图框中加载前3个客户及其名称对应的现金值。
在文本文件中有许多数字,例如交易号,现金存款金额,利息后现金金额。我如何区分这些,以便它只是在感兴趣后找到前3个现金金额并显示名称?
private void Form5_Load(object sender, EventArgs e)
{
int[] array = new int[10];
Console.WriteLine("transactions.txt");
for(int i=0;i<10;i++)
{
array[i] = Convert.ToInt32(Console.ReadLine());
}
int largest = array[9];
for(int i=0;i<10;i++)
{
if (array[i] > largest)
{
largest = array[i];
}
}
Console.WriteLine("The largest transaction amount is {0}", largest);
Console.Read();
}
//Here is the code for whats in the transactions.txt file.
public void CreateFile()
{
StreamWriter outputFile;
outputFile = File.AppendText("transactions.txt");
outputFile.WriteLine("Transaction Number :" + " " + TransactionIDLabel.Text);
outputFile.WriteLine("Investor :" +" " + InvestorNameLabel.Text);
outputFile.WriteLine("Initial Amount" + " " +AmountLabel.Text);
outputFile.WriteLine("Date Invested" +" " +DateLabel.Text);
outputFile.WriteLine("Period Chosen" + " "+DaysInvestedLabel.Text);
outputFile.WriteLine("Rate Chosen" + " " + RateLabel.Text);
outputFile.WriteLine("Total Interest" + " " +InterestAmountLabel.Text);
outputFile.WriteLine("Total Amount" + " " + TotalAmountLabel.Text);
outputFile.WriteLine("");
outputFile.Close();
}
答案 0 :(得分:2)
您需要做的更改才能让您获得前3名
int[] largest
OrderByDescending
按降序对数组进行排序Take(3)
获取所需的交易希望这有帮助,
int[] largest = array.OrderByDescending( item => item).Take(3).ToArray();
int count = 1;
string msg = "The {0} largest transaction amount is {1}";
foreach (var element in largest)
{
Console.WriteLine(msg, count++,element);
}
以下是listbox和listview的示例代码
private void button1_Click(object sender, EventArgs e)
{
int[] array = new int[] { 1, 3, 4, 5, 6, 7, 8, 99, 22, 44 };
int[] largest = array
.OrderByDescending(item => item)
.Take(array.Length).ToArray();
foreach (var element in largest)
{
listBox1.Items.Add(element);
listView1.Items.Add(new ListViewItem(element.ToString()));
}
}
这就是它的样子
答案 1 :(得分:0)
我建议将每一行读入一个对象/结构实例,然后使用类似
的内容获取前三行新列表([如果你仍然使用数组来保存它们])。OrderByDescending(x =&gt; x.Amount).Take(3);