Thursday, September 30, 2010

listFind vs. listContains

ColdFusion has two functions for finding things in comma-delimited lists, but they behave very differently, and I can never which is which.  Today I needed one of them, and so I did a test to figure out which I needed.  If figured I would document their usages here, so that I wouldn't have to go thru this testing process next time.  Here are the functions:

listContainsNoCase(list, substring)
This function just finds the substring, and tells you which item contains that sub string.  It is important to understand that this item is not searching for a list item, just for a sub string.  Consider the following example:
listContainsNoCase("Date,Decimal,Image,Integer,Long Text,Rich Text,Simple Text", "Text")=5
Notice how it found that item number 5 has the word "Text" in it, even though "Text" is not the complete item.

listFindNoCase(list, value)
This function finds a value in a list, and tells you which item matches the value.  It compares the value to the list item, and only accepts complete matches.  So, consider the following examples:
listFindNoCase("Date,Decimal,Image,Integer,Long Text,Rich Text,Simple Text", "Text")=0
listFindNoCase("Date,Decimal,Image,Integer,Long Text,Rich Text,Simple Text", "Simple Text")=7
Notice how in the first example above, no item was found.  This is because there is no single item with value = "Text".  However, it did find "Simple Text" in the second example above.

Of course the same is true for listFind, and listContains, but those are case-sensitive.

Incidentally, I put this one in the "duh" category, because I think that the names are reversed.  The first usage should be named listFind, and the second should be named listContains.

Hope this helps.

3 comments:

anna harris said...

Good comparison between this two functions. I have yet to see a good need for listContains, and every code block I've seen using it really wanted listFind instead!

Unknown said...

Here you go: a URL parameter that contains a list of object ids and their last updated dates. The objects are content from a CMS. You only want to respond to the call with objects that are new or are updated. my list is populated with items that are the object id (uuid) and the last updated date, separated by pipe (|). So with listContains I can look for the object id without having to iterate over the list, getListitem on each to extract the object id from the concatenated string that is the list item. If the object id is found then I can get that one item and compare the dates. If it's not found then it is a new object to send to the caller.

Anonymous said...

4 years later, but a valid use case of ListContains is traversing through active directory results. I needed to retrieve a name that may or may not be in a manager field. If there's a "CN=" substring, I can refer to its list position to retrieve the content and strip off the cruft.