C# Replace Item in List<String> "/"

How to replace list item in best way

Use Lambda to find the index in the List and use this index to replace the list item.

List<string> listOfStrings = new List<string> { "abc", "123", "ghi" };

int index = listOfStrings.FindIndex(s => s == "123");

if (index != -1)
listOfStrings[index] = "def";

C# replace item in list<string> "/"

The main problem is that your question is not too clear.
You want to replace one string with 4 strings.

1-A

becomes

1-\
2-p
3-\
4-;

in your example.

List<string> changeOne = new List<string>
for (int i=0;i<msg.Count();i++)
{
if (msg[i] == "A")
{
changeOne.AddRange( new [] {"\\","p","\\",";" });
}
else
{
changeOne.Add(msg[i]);
}
}

Best way to replace a Item in a List by ID

If you need to do a full replacement and not just an update (you could simply find the object, and copy properties one by one), you can save yourself a bit of trouble by finding its index and then replacing it directly, rather than removing, adding, and reordering.

int index = items.FindIndex(item => item.ID == replacement.ID);
if (index >= 0)
{
items[index] = replacement;
}

The replacement will be in the same spot as the original.

Replace a object in a list of objects

You have to replace the item, not the value of customListItem2. Just replace following:

customListItem2 = customListItems.Where(i=> i.name == "Item 2").First();
customListItem2 = newCustomListItem;

With this:

customListItem2 = customListItems.Where(i=> i.name == "Item 2").First();
var index = customListItems.IndexOf(customListItem2);

if(index != -1)
customListItems[index] = newCustomListItem;

Edit:

As Roman R. stated in a comment, you can replace the .Where(predicate).First() by a simple First(predicate):

customListItem2 = customListItems.First(i=> i.name == "Item 2");

Replace string in the list of string

For collections with indexers(Array or List), you can do it in one loop

for(var i = 0; i < values.Length; i++)
{
if (i > 0 && values[i - 1] == "$id")
{
values[i - 1] = values[i];
}
}

For any type of collection you can use enumerator to "loop" the collection only once and have access to current and previous element.

Approach below supports multiple occurrences of "$id" as well.

public static IEnumerable<string> ReplaceTemplateWithNextValue(
this IEnumerable<string> source,
string template
)
{
using (var iterator = source.GetEnumerator())
{
var previous = default(string);
var replaceQty = 0;
while (iterator.MoveNext())
{
if (iterator.Current == "$id") replaceQty++;

if (previous == "$id" && iterator.Current != "$id")
{
for (var i = 0; i < replaceQty; i++) yield return iterator.Current;
replaceQty = 0;
}

if (iterator.Current != "$id") yield return iterator.Current;

previous = iterator.Current;
}

if (previous == $"$id")
{
for (var i = 0; i < replaceQty; i++) yield return previous;
}
}
}

Usage

var list = new List<string>() { "test", "$id", "central" };

var replaced = list.ReplaceTemplateWithNextValue("$id");
// => { "test", "central", "central" }

Supported cases:

[Fact]
public void TestReplace()
{
ReplaceId(Enumerable.Empty<string>()).Should().BeEmpty(); // Pass
ReplaceId(new[] { "one", "two" })
.Should().BeEquivalentTo(new[] { "one", "two" }); // Pass
ReplaceId(new[] { "$id", "two" })
.Should().BeEquivalentTo(new[] { "two", "two" }); // Pass
ReplaceId(new[] { "one", "$id", "two" })
.Should().BeEquivalentTo(new[] { "one", "two", "two" }); // Pass
ReplaceId(new[] { "one", "two", "$id" })
.Should().BeEquivalentTo(new[] { "one", "two", "$id" }); // Pass
Replace(new[] { "one", "$id", "$id" })
.Should().BeEquivalentTo(new[] { "one", "$id", "$id" }); // Pass
}

Replace the last occurrence of a word in a string - C#

Here is the function to replace the last occurrence of a string

public static string ReplaceLastOccurrence(string Source, string Find, string Replace)
{
int place = Source.LastIndexOf(Find);

if(place == -1)
return Source;

string result = Source.Remove(place, Find.Length).Insert(place, Replace);
return result;
}
  • Source is the string on which you want to do the operation.
  • Find is the string that you want to replace.
  • Replace is the string that you want to replace it with.

C# List<(string,string)> matching and replacing values

You can use LINQ with Where and Select looking like this:

var list1 = new List<(string, string)>
{
("great cause", "1"), ("hyper sensitive", "2"), ("increased pertinance", "3"), ("greater sensitive", "4")
};

var list2 = new List<string>{"cause", "greater", "hyper", "pertinance"}; // fixed typos from the post.
var result = list2
.Where(s => list1.Any(t => t.Item1.Contains(s)))
.Select(s => list1.First(t => t.Item1.Contains(s)).Item2)
.ToList();
Console.WriteLine(string.Join(", ", result)); // prints "1, 4, 2, 3"

C# string replace does not actually replace the value in the string

The problem is that strings are immutable. The methods replace, substring, etc. do not change the string itself. They create a new string and replace it. So for the above code to be correct, it should be

path1 = path.Replace("\\bin\\Debug", "\\Resource\\People\\VisitingFaculty.txt");

Or just

path = path.Replace("\\bin\\Debug", "\\Resource\\People\\VisitingFaculty.txt");

if another variable is not needed.

This answer is also a reminder that strings are immutable. Any change you make to them will in fact create a new string. So keep that in mind with everything that involves strings, including memory management.
As stated in the documentation here.

String objects are immutable: they cannot be changed after they have
been created. All of the String methods and C# operators that appear
to modify a string actually return the results in a new string object



Related Topics



Leave a reply



Submit