Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace some particular string in a list of type string using linq?

Tags:

c#

linq

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
}
like image 444
sreenu Avatar asked Nov 09 '11 09:11

sreenu


People also ask

How can I replace part of a string in C#?

C# String Replace()The Replace() method returns a new string by replacing each matching character/substring in the string with the new character/substring.

How do I change the value of a string in a list?

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 .

What is any () in Linq?

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.

Can you use Linq on a string?

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.


1 Answers

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");
like image 69
Blau Avatar answered Sep 20 '22 17:09

Blau