C# Find using contains and replace exact match

T.Zacks 3,986 Reputation points
2021-03-21T08:07:40.373+00:00

Thanks for your example.

Here i am finding and replace. how to replace exact work. please suggest.

xdcBrokerFiles = XDocument.Load(@f);
popUpStandardLineItem = from item in xdcBrokerFiles.Descendants().Elements("TickerBrokerLineItemMap")
                        where item.Element("Formula").Value.Contains(olditem.Trim())
                            select item;

foreach (var data in popUpStandardLineItem)
{
    data.Element("Formula").Value.Replace(olditem.Trim(),newitem.Trim());
    xdcBrokerFiles.Save(@f);
}

see this line data.Element("Formula").Value.Replace(olditem.Trim(),newitem.Trim()); where problem may occur during replace data in xml. so how to handle this kind of replace?

Thanks

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,190 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Ken Tucker 5,846 Reputation points
    2021-03-21T10:53:28.687+00:00

    You will need to change your code to something like this. String.Replace will replace any part of the string that matches the old value with the new value

     foreach (var data in popUpStandardLineItem)
     {
             if( data.Element("Formula").Value.Trim() == olditem.Trim())
             {
                       data.Element("Formula").Value = data.Element("Formula").Value.Replace(olditem.Trim(),newitem.Trim());
                     xdcBrokerFiles.Save(@f);
              }
     }
    
    1 person found this answer helpful.