I'm trying to compare the values of my dictionary and display my results like this.
Field Values Mismatch For Field: Expected:001 Actual:002
Field Values Mismatch For Field: Expected:003 Actual:002
I'm able to get the difference for each of the rows in my dictionary but I'm not sure how to display my result in string list.
This is what I have try
public static string ValidateMvpFields(string value1, Dictionary<string, ValueMap> value2)
{
var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(value1);
foreach (var item in value2.Keys)
{
try
{
var Val1 = xmlDoc.SelectSingleNode(responseParameters[item].XPath).InnerText;
var Val2 = responseParameters[item].Value;
if (!Val1.Trim().Equals(Val2.Trim()))
{
var results = ErrorMessage = $"Mvp Field Values Mismatch For Field: {item} Expected:{Val1} Actual:{Val2}";
string result = null;
result += String.Join(Environment.NewLine, results);
}
continue;
}
catch (Exception ex)
{
var results = ErrorMessage = $"Invalid Xpath: {value2[item].XPath} For Field:{item} Error:{ex.Message}";
/*return results*/
;
}
}
return "";
}
Here is an example of my dictionary
public static Dictionary<string, ValueMap> Example = new Dictionary<string, ValueMap>
{
{"Example1", new ValueMap { XPath = "", Value = "5123"} },
{"Example2", new ValueMap { XPath ="", Value = "123"} },
}
Instead of initializing string result = null
inside for loop, Initialize StringBuilder
outside of for
loop and append each result to it.
Initialization of string result = null
everytime is creating new string variable every time and you are unable to get previously stored result while iterating inside for loop.
public static string ValidateMvpFields(string value1, Dictionary<string, ValueMap> value2)
{
var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(value1);
StringBuilder sb = new StringBuilder(); //Initialize StringBuider
foreach (var item in value2.Keys)
{
try
{
var Val1 = xmlDoc.SelectSingleNode(responseParameters[item].XPath).InnerText;
var Val2 = responseParameters[item].Value;
if (!Val1.Trim().Equals(Val2.Trim()))
{
var results = ErrorMessage = $"Mvp Field Values Mismatch For Field: {item} Expected:{Val1} Actual:{Val2}";
//Append new value every time into string builder
sb.Append(Environment.NewLine);
sb.Append(results);
}
continue;
}
catch (Exception ex)
{
var results = ErrorMessage = $"Invalid Xpath: {value2[item].XPath} For Field:{item} Error:{ex.Message}";
/*return results*/
;
}
}
return "";
}
string
type is immutable, when ever you assign new value to string it creates new object, StringBuilder
is immutable so it helps to avoid memory leak.
If you want to store result in a list then use List<string>
and add new result every time, like
List<string> results = new List<string>(); //Initialize list
……
results.Add(result); //Add new value to it