0

I have an implicit variable taking a List containing the result of a SQL query (LINQ). This set represents the existing clients of a list, previously selected.
Through a stored procedure I take a new set of clients that will be used to fill a drop down. Iterating through this set of data I exclude those records if already contained in the list of existing entries.

How could I do this check with implicitly typed variables?

var existingClients = (from doc in TBL_Documents
                       join c in TBL_CONTACT on doc.CONTACTID equals c.CONTACTID
                       where doc.DOCID.Equals(DocID)
                       select new { c.CONTACTID, c.FULLNAME }).ToList();


 var resultSet = sp_ActiveContacts(index).ToList();
 foreach (var record in resultSet)
 {
   //How could I achieve something like this if condition (like a List)?
   if (!existingClients.Contains(record.CONTACTID))            
   {                                
      optionTags += "<option value=" + record.CONTACTID + ">" + record.Name + "</option>";
   }                       
 }

If possible, I would prefere avoiding to create a temporary List to store the CONTACTID used for the if condition.

skaffman
  • 398,947
  • 96
  • 818
  • 769
Francesco
  • 9,947
  • 7
  • 67
  • 110

2 Answers2

2

Anonymous types test for equality by checking each property, so you could do this:

if (!existingClients.Contains(new { record.CONTACTID, record.FULLNAME }))

(Assuming your record variable has a FULLNAME property. Otherwise just construct the anonymous object with the appropriate values.)

See this answer for more info.

Edit

Easier still might be:

if (!existingClients.Any(c => c.CONTACTID == result.CONTACTID))
Community
  • 1
  • 1
Matt Hamilton
  • 200,371
  • 61
  • 386
  • 320
  • That's definitively much more readable. And it is not needed to create the other values related to record variable (result in your example). – Francesco Jul 29 '11 at 12:57
0

Thanks Matt for the good answer! In terms of performance what would be the difference between your suggestion and using a temporary List to store the IDs and make the check over this list?

...
List<Guid> existIDs = new List<Guid>();
foreach (var c in existingContacts)
{
  existIDs.Add(c.CONTACTID);
}

var resultSet = db.sp_PagingActiveContacts(idx, userLogin, range).ToList();
foreach (var record in resultSet)
{
if (!existIDs.Contains(new {record.CONTACTID}))
{  ....
Francesco
  • 9,947
  • 7
  • 67
  • 110
  • 1
    I don't think you gain anything by doing it this way. The .Any() call will be almost as quick and IMHO is more readable. – Matt Hamilton Jul 29 '11 at 12:01