我有一个长度为3的数组说Array(3,4,5)
我的目标长度是Int
说的7.如何用Array
填充Array
元素直到Int
的长度达到val A = Array(3,4,5)
val T = 7
//Desired output Array(3,3,3,3,3,4,5)
?
val difflength = T - A.size
val firstElement = A.head
val PadArray = (for(i <- 0 to difflength) yield firstElement).toArray
PadArray ++ A
我目前的方法:
namespace WinFormsApp
{
public partial class Form1 : Form
{
private List<Category> categories;
public Form1()
{
InitializeComponent();
categories = new List<Category>();
var categoryOne = new Category { Name = "Category 1"} ;
categoryOne.Items.Add( new CategoryItem { Name = "Item 1"} );
var categoryTwo = new Category { Name = "Category 2" };
categoryTwo.Items.Add( new CategoryItem { Name = "Item 2" } );
categories.Add( categoryOne );
categories.Add( categoryTwo );
}
private void Form1_Load(object sender, System.EventArgs e)
{
categoryBindingSource.DataSource = categories;
}
}
public class Category
{
public string Name { get; set; }
public List<CategoryItem> Items { get; private set; }
public Category()
{
Items = new List<CategoryItem>();
}
}
public class CategoryItem
{
public string Name { get; set; }
}
}
有更简单的方法吗?
答案 0 :(得分:3)
Array
's fill
method可以派上用场:
val a = Array(3,4,5)
val b = {
val t = 7
val diffLength = t - a.size
val firstElement = a.head
Array.fill(diffLength)(firstElement) ++ a
}
结果:
scala> b
res0: Array[Int] = Array(3, 3, 3, 3, 3, 4, 5)