tags:

views:

76

answers:

2

I have a List of integers

 List<int> LI = new List<int>();

i wants check whether a particular number exists in the list.if exists do a database updation else do a database insert

foreach (int IT in LI)
        {

        }

can i do this inside the foreach loop or if not possible how to achieve this?????

+5  A: 

The easiest way is:

if(LI.Contains(someIntValue))
{
  // do database update
}

Which will search every element in the list and compare it to someIntValue, and return true once an element that matches is found, or false if no element matches.

Now, this is inefficient because the time to search a list is linear. If you are constantly searching your list you should probably be storing your integers in a collection that is better suited for searching such as Dictionary or HashSet which both have constant time

Alan
Thanks for the reply Alan.My List is not a long one.it can contain 20-25 elements so what's the collection i should use and what is the efficiency of Dictionary or HashSet over List
chamara
+1 for mentioning better suiting data structures for this problem. [Here](http://dotnetperls.com/dictionary-time) you'll find a comparison between the lookup time of a `Dictionary` and the one of a `List`
Giu
@chamara: If you're using .NET 3.5 or newer then use HashSet, as it is specific to searching. Dictionary is a more appropriate collection for to associating keys with values. If you're using .Net 3.0 or older, use Dictonary.
Alan
@Giu: Interesting link, but it assumes `int`. A search on `string` is likely to have a somewhat different break-even point.
Steven Sudit
+2  A: 
public void InsertUpdateNumber(int i){

    if(LI.Any(li => li == i))
        //do update
    else
        //do insert

}
Rony
Overkill much? :-)
Steven Sudit
a bit for this scenario but can be extended to complex scenarios with the same logic, like for ex: check for existence of an employee and department combination in a list of employee Information data
Rony