Home > database >  How can I add to every item(string) inside of the List<int, string> dymanic id(int) which is a
How can I add to every item(string) inside of the List<int, string> dymanic id(int) which is a

Time:02-18

I need to add an id/key to every element inside of the List<int, string>. I tried method with static id:

for (int i = 0; i < sen.Length; i  )
            {
                mySentences.Add(new Values { ID = i, Sentence = sen[i] });

            }

But then there are apperaing some problems with this method. I want to delete for example item from the middle of list, then every item under the deleted item should change it`s id to (n - 1). So how I can apply to this dynamic id?

CodePudding user response:

You can use this method to reindex your List on every delete.

public List<Values> ReindexAfterDelete(List<Values> sen) 
    {           
        for (int i = 1; i<= sen.Count; i  ) { 
            sen[i-1].ID = i;
        }
        return sen;
    }

CodePudding user response:

You can add a reference to the list in every item you store in the list. If you access the ID property, you can just get the index of your list via IndexOf method from List<T>:

public class Sentence
{
   private List<Sentence> list;

   public int ID
   {
     get
     {
       return list.IndexOf(sentence);
     }
   }

   public Sentence(List<Sentence> list)
   {
      this.list = list;
   }
}

Usage is:

List<Sentence> mySentences = new List<Sentence>();
Sentence sentence  = new Sentence(mySentences)
mySentences.Add(sentence  );

This approach has two disadvantages: First, every access of the ID property is O(n), which could lead to performance issues if you have a list with many items. Second, it won't work if you add the same sentence twice to the list.

On the other hand, the big advantage is that you won't get any trouble updating the ID after every insert, remove and so on. You can rely that the ID is always correct.

  • Related