你好,我是一个新的程序员,我正在尝试格式化数组的方式,在一个特定的数组的结尾有一个换行符。我目前有4个单独的数组,我想在其中排列数组中的每个项到一个特定的模式。我已经完成了这项任务,但现在我被难倒了,因为他们都在一条线上。让我给你举个例子:(顺便说一下,我在datagridview上这样做)
(This is what I want to happen)
Binder Clips Small pc 12 1260
Selleys All Clear pc 12 2400
(This is what I am getting)
Binder Clips Small pc 12 1260 Selleys All Clear pc 12 2400
这是我的代码:
//I get these from a datagridview
var items = carto.Rows
.Cast<DataGridViewRow>()
.Select(x => x.Cells[1].Value.ToString().Trim())
.ToArray();
var units = carto.Rows
.Cast<DataGridViewRow>()
.Select(x => x.Cells[2].Value.ToString().Trim())
.ToArray();
var quantity = carto.Rows
.Cast<DataGridViewRow>()
.Select(x => x.Cells[6].Value.ToString().Trim())
.ToArray();
var prices = carto.Rows
.Cast<DataGridViewRow>()
.Select(x => x.Cells[8].Value.ToString().Trim())
.ToArray();
//this is what I use to sort out the pattern that I want the arrays to be in
string[] concat = new string[items.Length * 4];
int index = 0;
for (int i = 0; i < items.Length; i++)
{
concat[index++] = items[i];
concat[index++] = units[i];
concat[index++] = quantity[i];
concat[index++] = prices[i];
}
// and this is where I am stuck because I can just put \n, it would ruin the format even more
cartitems.Text = string.Join(" ", concat);
我也试着做了这样的事情:
int j = 0;
string str = "";
foreach (var item in concat)
{
str += item;
if (j <= concat.Length - 1)
{
if (j % 3 == 0)
str += " ";
else
str += "\n";
}
j++;
}
这就总结了我的问题,我真的希望你能帮助一个像我这样的新手,我有一种感觉,答案很简单,我只是没有经验。
C#是一种面向对象的语言,所以我们不妨利用这一点,对吧?
为项目创建类。
class Item
{
public string Name { get; set; }
public string Unit { get; set; }
public string Quantity { get; set; }
public string Price { get; set; }
public void WriteLine(TextWriter writer) {
writer.WriteLine($"{Name} {Unit} {Quantity} {Price}");
}
}
这就是加载数组的方式。
Item[] concat = new Item[items.Length];
int index = 0;
for (int i = 0; i < items.Length; i++) {
concat[index++] = new Item {
Name = items[i],
Unit = units[i],
Quantity = quantity[i],
Price = prices[i]
};
}
这就是如何将它写入控制台的。
foreach(Item item in concat) {
item.WriteLine(Console.Out);
}
写到文件而不是写到控制台是一个一行的更改。
作为一般规则,您应该将数据结构(数据的存储方式,在这里实现为一个数组)与数据表示(在本例中,写入控制台或文件,在这里由Item.WriteLine方法实现)分开。