Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# way to add value in a List<T> at index

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

 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 
like image 933
TyGerX Avatar asked Apr 23 '12 17:04

TyGerX


2 Answers

The .Insert() method on List<T> is exactly for this purpose:

someList.Insert(2, someValue); 

This would modify the someList collection to insert someValue at index 2, pushing other values up one index.

More information here.

like image 84
David Avatar answered Sep 25 '22 14:09

David


List<T>.Insert, perhaps?

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:

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.

like image 35
Jon Skeet Avatar answered Sep 26 '22 14:09

Jon Skeet