15

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
}
0

3 Answers 3

22

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");
Sign up to request clarification or add additional context in comments.

Comments

8
static class LinqExtensions
{
    public static IEnumerable<T> Replace<T>(this IEnumerable<T> items, Predicate<T> condition, Func<T, T> replaceAction)
    {
        return items.Select(item => condition(item) ? replaceAction(item) : item);
    }
}

Then you can use it like so

var names = new[] { "Hasan", "Jack", "Josh" };
names = names.Replace(x => x == "Hasan", _ => "Khan").ToArray();

1 Comment

+1 Elegant and first time I see a lambda without params defined that way ... everyday I learn something new :)
7
List<String> lstString = new List<string> { "find", "find1","find", "find2" };

//all 'find' will be replaced with 'replace'
lstString.Select(str=>str.Replace("find","replace"));

3 Comments

This is not doing the operation requested.
@Blau: Herein I propose a solution which can be tailored further for any specific business problem.
hehehe, of course, but this question is specific enough... he wants to replace full strings, and replace method will replace substrings too... ;)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.