-3

How to check a list contains a string or any number followed by that string? I need to add string in a list. While adding it in the list I have to check whether that string is already exists in that list. If so need to insert that string with integer count. That is if name is already exists means it should be inserted as "Name1". If again I am adding Name means it should be inserted as name2. and so on... How can I achieve this?

List<Names> NameList=new List<Names>();

Name name=new Name();
name.Name="Name";
NameList.Add(Name);

Name name1=new Name();
name1.Name="Name";
NameList.Add(Name1);

Name name2=new Name();
name2.Name="Name";
NameList.Add(Name2);

Public class Name
{
 string Name {get;set; }
}
Devi
  • 336
  • 1
  • 5
  • 12
  • 1
    Try sharing your actual code for better answers - the sample you posted won't compile. Also try reading through your question again. Would it be easy for you to understand if you were the answerer and knew nothing about your code base ? – driis Jul 24 '12 at 18:55
  • Your lastly edited code wouldn't compile also. See `Names` and `Name`. – L.B Jul 24 '12 at 19:26

2 Answers2

1

Your code won't compile, but I am assuming you are talking about a List<string>. If so, the algorithm could be:

string val = "Name";
string toInsert = val;
int n = 1;
while(list.Contains(toInsert))
{
   toInsert = val + n++;
}
list.Add(toInsert);
driis
  • 161,458
  • 45
  • 265
  • 341
  • Seems like it will work, but it leaves a sour taste in my mouth. Seems like there is a better way to structure the whole thing to avoid N linear searches... – Servy Jul 24 '12 at 18:59
  • Actually, this won't work. Let's say the list contains "Cat". If I call this to insert "Cat", it will add "Cat1". If I call again to insert "Cat", it will insert "Cat1" not "Cat2". List.Contains() actually does an itemwise == comparison, not an itemwise .contains (after all, List can't expect every type to implement a Contains method). – iheanyi Feb 25 '14 at 18:41
0

You should take a look into the HashSet<T> class.

With this you can make your lookup in O(1). But be aware, that this uses the methods Equals() and GetHashCode() of your class to check for equality. So either put simple strings into the set for checking or write a appropriate IEqualityComparer for your Name class and put an instance of it into the constructor of your hashset. If you need assistance to write a good GetHashCode implementation take a look into this SO question.

Community
  • 1
  • 1
Oliver
  • 43,366
  • 8
  • 94
  • 151