You are viewing limited content. For full access, please sign in.

Question

Question

Using RA, how to not add a duplicate value to a particular field

SDK
asked on February 3, 2014

I am using the following code to add values to specific multi-value fields:

 

foreach (var Value in updateFields.multiValueFieldsAndValues)
{
    fieldValueCollection.AppendValues(Value.multiValueFieldName, Value.multiValueFieldValues);

}

 

However, I don't want to add a duplicate value to a multi-valued field that already contains that value.  What is the correct way to achieve this?  Because if I call my code twice, I end up with duplicates in the field values.

0 0

Answer

APPROVED ANSWER
replied on February 3, 2014

Based on your question, it sounds like you have an existing document that has some values in this field, and you have some collection of values that you'd like in the field, but you don't know if the two overlap. You'd like all values that are both in your new collection, and already existing on your document, but you don't want any duplicates. The type of data structure that does this is called a Set, and in .Net the class to use for that is a HashSet.

 

I'll assume that you already have a DocumentInfo for your document, an IEnumerable<object> that contains the new values, and the string name of the field.

 

DocumentInfo info;
IEnumerable<object> newValues;
string multiValueFieldName;

// First, get the existing values already on the document
// Note that we can cast to IEnumerable<object> because we know 
// that the field is a multivalue field

IEnumerable<object> oldValues = 
    (IEnumerable<object>)info.GetFieldValue(multiValueFieldName);

// Construct our HashSet
ISet<object> values = new HashSet<object>();

// Put all of the values, old and new, into the set.
// Since it is a Set, if we add a value twice it will only contain it 
// once!

foreach (object value in newValues)
    values.Add(value);

foreach (object value in oldValues)
    values.Add(value);

// Finally, we gather the collected values into a FieldValueCollection 
// and set the document's value

FieldValueCollection fieldCollection = new FieldValueCollection();

// Note the ToArray call
fieldCollection[multiValueFieldName] = values.ToArray();

info.SetFieldValues(fieldCollection);

// Persist changes
info.Save();

// Always call Dispose on the DocumentInfo when you're done with it!
info.Dispose();

 

Hopefully this answers your question!

0 0

Replies

replied on February 3, 2014

First, you must build your code to retrieve the content of the multi-value field.  Then run a check to see if the field already contains the value you are wanting to add.  If the value is not already contained in the field, then proceed to add it.

0 0
replied on February 3, 2014

Thank you!

0 0
You are not allowed to follow up in this post.

Sign in to reply to this post.