C# 将数组的第一个元素添加到同一数组中
我有一个对象数组。我需要将该数组的第一个元素添加到它的末尾,这样第一个元素和最后一个元素是相同的。我想到了这个,但我觉得有更好的解决办法C# 将数组的第一个元素添加到同一数组中,c#,arrays,concatenation,elements,C#,Arrays,Concatenation,Elements,我有一个对象数组。我需要将该数组的第一个元素添加到它的末尾,这样第一个元素和最后一个元素是相同的。我想到了这个,但我觉得有更好的解决办法 points.Concat(新[]{points[0]}).ToArray() 完整背景: public static Vertex[] CreateLineStrip(Color color, params Vector2f[] points) { return CreateVertices(color, points.Concat(new[] {
points.Concat(新[]{points[0]}).ToArray()
完整背景:
public static Vertex[] CreateLineStrip(Color color, params Vector2f[] points)
{
return CreateVertices(color, points.Concat(new[] { points[0] }).ToArray());
}
CreateVertices
将给定的点数组投影到一个顶点数组。如果使用以下扩展方法,可以在注释中添加一些语法
然而,除了一个崭新的扩展方法之外,这里并没有什么真正的收获
public static class ArrayExtensions
{
static public T[] Append<T>(this T[] array, T item)
{
return array.Concat(new[] { item }).ToArray();
}
}
public static Vertex[] CreateLineStrip(Color color, params Vector2f[] points)
{
return CreateVertices(color, points.Append(points[0]));
}
公共静态类ArrayExtensions
{
静态公共T[]追加(此T[]数组,T项)
{
返回array.Concat(new[]{item}).ToArray();
}
}
公共静态顶点[]CreateLineStrip(颜色、参数向量2f[]点)
{
返回CreateVertices(颜色、点.Append(点[0]);
}
公共void MyMethod(参数Contact[]contacts)
{
var列表=新列表(联系人);
list.Add(list[0]);
//做你自己的事
}
如果需要不同数量的元素,我不会首先使用数组。您不能使用列表的原因是什么?然后:list.Add(list[0])
@JonSkeetpoints
用作方法的params
参数。我可以将列表与params
一起使用吗?您的意思是它来自params
参数吗?如果能了解更多的情况就好了。(即使你以数组开始,或以数组结束,这并不意味着你在每个阶段都需要它作为数组…)我已经为我的问题添加了完整的上下文。问题是你是否需要像这样到处使用数组。当然,您现有的代码非常简单。绩效对你有多重要?
public void MyMethod(params Contact[] contacts)
{
var list = new List<Contact>(contacts);
list.Add(list[0]);
// ... do your thing
}