简体   繁体   中英

List<String> find and replace values by part of string

I have a List<String> which contains values like Char:Char_Number1_Number2 . I want to find the index or replace the value , by searching Number1_Number2 , the combination of Number1_Number2 is always unique.

EG: B:S_4_0 will be replaced as B:S_5_1 , But searching criteria is 4_0

B:S_4_0
B:N_1_2
A:N_3_3
B:N_0_0
A:S_2_5
A:S_3_4

I want these tasks

  1. How to find the index or complete value by using the second half of the string
  2. How to replace or remove a specific value by using the second half of the string

int index = Player1.IndexOf("5_6");    // Find Index
Player1[index]="5_6";                  // Replace value
Player1.Remove("5_6");                 // Remove 

References

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

How to replace list item in best way

C#: Update Item value in List

This will replace B:S_4_0 by B:S_5_1 , serching for 4_0

List<string> lstString = new List<string> {"B:S_4_0", "B:N_1_2", "A:N_3_3", "B:N_0_0", "A:S_2_5", "A:S_3_4"};

int j = lstString.FindIndex(i => i.Contains("4_0")); //Finds the item index

lstString[j] = lstString[j].Replace("4_0", "5_1"); //Replaces the item by new value
int index = list.FindIndex(i => i.Contains("4_0"));

list[index] = list[index].Replace("4_0", "5_6");

Hope this will help :)

Find index (returns -1 if not found):

int index = list.FindIndex(s => s.EndsWith("4_0"));

Replace:

list[index] = list[index].Replace("4_0", "5_1");

Remove:

list.RemoveAt(index);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM