Hi all I have list of type string with some items. i want to replace some items using linq, how can i do that? my below code is working fine but i want to do this in single line of code using the power of linq.
Here is my code :
List<string> listcolumns = columns.ToList();//Array to list
if (listcolumns.Contains("HowToReplace") && listcolumns.Contains("HowTo Replace"))
{
int index = 0;
index = listcolumns.IndexOf("HowToReplace");
if (index > 0)
{
listcolumns.RemoveAt(index);
listcolumns.Insert(index, "HowTo Replace");
}
index = listcolumns.IndexOf("HowToReplace");
if (index > 0)
{
listcolumns.RemoveAt(index);
listcolumns.Insert(index, "HowTo Replace");
}
columns = listcolumns.ToArray<string>();//List to array
}
C# String Replace()The Replace() method returns a new string by replacing each matching character/substring in the string with the new character/substring.
Replace a specific string in a list. If you want to replace the string of elements of a list, use the string method replace() for each element with the list comprehension. If there is no string to be replaced, applying replace() will not change it, so you don't need to select an element with if condition .
The Any operator is used to check whether any element in the sequence or collection satisfy the given condition. If one or more element satisfies the given condition, then it will return true. If any element does not satisfy the given condition, then it will return false.
LINQ can be used to query and transform strings and collections of strings. It can be especially useful with semi-structured data in text files. LINQ queries can be combined with traditional string functions and regular expressions.
With Linq:
listColumns.Select<string,string>(s => s == "HowToReplace" ? "HowTo Replace" : s).ToArray();
Without Linq:
for (int i=0; i<listColumns.Length; i++)
if (ListColumns[i] == "HowToreplace") ListColumns[i] ="HowTo Replace");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With