Following is the code sample that can be used to remove a duplicate array from JArray.
private static string RemoveDuplicateTasks(JArray strArray)
{
JArray uniqueArray = new JArray();
StringBuilder jsonResponse = new StringBuilder();
//Loop through each array and find for array value with a specific column name. (ex: ID)
foreach (JObject jObject in strArray)
{
//Verify if the ID column value exist in the uniqueArray
JObject rowObject = uniqueArray.Children<JObject>().FirstOrDefault(o => o["id"] != null && o["id"].ToString() == jObject.Property("id").Value.ToString());
//rowObject will be null if these is no match for the value in ID column
if (rowObject == null)
{
uniqueArray.Add(jObject);
}
}
//Remove the curly braces { }
int strLength = uniqueArray.ToString().Length;
string strValue = uniqueArray.ToString().Substring(1, (strLength - 2));
jsonResponse.Append((jsonResponse.Length > 0 ? "," : "") + strValue);
return "[" + jsonResponse.ToString() + "]";
}
private static string RemoveDuplicateTasks(JArray strArray)
{
JArray uniqueArray = new JArray();
StringBuilder jsonResponse = new StringBuilder();
//Loop through each array and find for array value with a specific column name. (ex: ID)
foreach (JObject jObject in strArray)
{
//Verify if the ID column value exist in the uniqueArray
JObject rowObject = uniqueArray.Children<JObject>().FirstOrDefault(o => o["id"] != null && o["id"].ToString() == jObject.Property("id").Value.ToString());
//rowObject will be null if these is no match for the value in ID column
if (rowObject == null)
{
uniqueArray.Add(jObject);
}
}
//Remove the curly braces { }
int strLength = uniqueArray.ToString().Length;
string strValue = uniqueArray.ToString().Substring(1, (strLength - 2));
jsonResponse.Append((jsonResponse.Length > 0 ? "," : "") + strValue);
return "[" + jsonResponse.ToString() + "]";
}
Very good and informative article, thanks for this posting..
ReplyDelete