Check if an Implicitly typed variable contains a specific value
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 p开发者_运维百科ossible, I would prefere avoiding to create a temporary List to store the CONTACTID used for the if condition.
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))
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}))
{ ....
精彩评论