C# 在 List<T> 索引处添加值的方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10284952/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# way to add value in a List<T> at index
提问by TyGerX
Is there any way you can add a value at a specific index? I try to do indexator and I have Lists. Is there any trick for making this this in this context :D
有什么方法可以在特定索引处添加值?我尝试做索引器,我有列表。在这种情况下有什么技巧可以做到这一点:D
public class Multime<T>
{
private List<Multime<T>> multiSets;
private List<T> multimea;
***public Multime<T> this[int index]
{
get { return this.Multisets.ElementAt(index); }
set { this.Multisets.CopyTo(value,index); }
}***
public List<Multime<T>> Multisets
{
get { return this.multiSets; }
set { this.multiSets = value; }
}//accesori Multimea de multimi
public List<T> Multimea
{
get { return this.multimea; }
set { this.multimea = value; }
}//Accesori Multime
采纳答案by Jon Skeet
List<T>.Insert, perhaps?
List<T>.Insert, 也许?
But I'd suggest you probably just want to fetch/write - not insert:
但我建议您可能只想获取/写入 - 而不是插入:
public Multime<T> this[int index]
{
get { return Multisets[index]; }
set { Multisets[index] = value; }
}
Note that as of C# 3, there are simpler ways of writing those properties, btw:
请注意,从 C# 3 开始,有更简单的方法来编写这些属性,顺便说一句:
public List<T> Multimea { get; set; }
public List<Multime<T>> Multisets { get; set; }
It's also not generally a good idea to actually expose composed collections directly - it means you have no control over what happens in those collections.
直接公开组合集合通常也不是一个好主意 - 这意味着您无法控制这些集合中发生的事情。
回答by Matthew
Can you use List.Insert?
你可以使用List.Insert吗?
回答by Saintt Sheldon Patnett
Try using List.Insert
尝试使用 List.Insert
This should solve the problem you are having.
这应该可以解决您遇到的问题。
回答by David
The .Insert()method on List<T>is exactly for this purpose:
在.Insert()对方法List<T>正是为了这个目的:
someList.Insert(2, someValue);
This would modify the someListcollection to insert someValueat index 2, pushing other values up one index.
这将修改someList集合以someValue在 index 处插入2,将其他值向上推一个索引。
More information here.
更多信息在这里。
回答by user3930061
You may be looking for something more like a Dictionary or Map. These are types of collections that allow you to assign an object using key value pairs so you can always assign an object at a certain position and retrieve it from that same position. You may think that you need the list because you don't know how many records you will store, but if you have some sense of the maximum number of records it will help you decide if you can use something like a Dictionary. The limit is pretty high I think, but you can look at the Dictionary class to see the limits.
您可能正在寻找更像是字典或地图的东西。这些是允许您使用键值对分配对象的集合类型,因此您始终可以在特定位置分配对象并从同一位置检索它。您可能认为需要该列表是因为您不知道将存储多少条记录,但是如果您对最大记录数有所了解,它将帮助您决定是否可以使用诸如字典之类的东西。我认为限制相当高,但您可以查看 Dictionary 类以了解限制。

