title: How do I test for a lookup list item, and add it if it is missing, in SharePoint 2007 via C#?
body: <p>Hi and thanks for looking!</p>
  <h1>Background</h1>
  <p>I am having trouble <strong>when I attempt to add a value to a lookup column</strong>.</p>
  <p>I am using SharePoint 2007 and the app has to run in .NET 2.0.  The language is C#.  <strong>Some lookup columns will allow multiple values.</strong></p>
  <h1>Question</h1>
  <p>Using C#, how do I do #'s 2-4 of the following:</p>
  <ol>
  <li>Attempt to add a list item to a SP list.</li>
  <li>For any lookup columns, check the SP List they are referencing to see if that list contains the value I am attempting to add.</li>
  <li>If the value DOES NOT exist in the lookup list, add it.</li>
  <li>Associate the newly added lookup value to the list item I was originally trying to add.</li>
  </ol>
  <p>I have been googling this, of course, but am still stuck.  Here is some code from Microsoft which is a start, but it is still not getting me going (not commented and not intuitive to me):</p>
  <pre><code>namespace ConsoleApp
  {
      class Program
      {
          static void Main(string[] args)
          {
              using (SPSite site = new SPSite(&quot;http://localhost&quot;))
              {
                  using (SPWeb web = site.RootWeb)
                  {
                      SPList customerList = web.Lists.TryGetList(&quot;Contoso Customers&quot;);
                      SPList orderList = web.Lists.TryGetList(&quot;Contoso Orders&quot;);
  
                      if (customerList != null &amp;&amp; orderList != null)
                      {
                          SPListItemCollection customers = customerList.Items;
                          SPListItemCollection orders = orderList.Items;
  
                          string fieldName = &quot;CustIDLookup&quot;;
                          if (!orderList.Fields.ContainsField(fieldName))
                              return;
                          
                          SPField lookupFld = orderList.Fields.GetField(fieldName);
  
                          foreach (SPListItem customer in customers)
                          {
                              SPListItem order = orders.Add();
                              order[SPBuiltInFieldId.Title] = &quot;Thank you!&quot;;
                              order.Update();
  
                              SPFieldLookupValue value = new SPFieldLookupValue(customer.ID, customer.ID.ToString());
                              order[lookupFld.Id] = value.ToString();
                              order.Update();
                          }
                      }
                  }
              }
          }
      }
  }
  </code></pre>
  <p>Even with Microsoft's examples, I can't get any real traction in figuring out how to actually do this.</p>
  <p>Your help is GREATLY appreciated.</p>