List <string>按字符串

时间:2016-02-13 06:39:11

标签: c# .net list data-structures

我有List<String>,其中包含Char:Char_Number1_Number2等值。 我希望找到索引替换值,通过搜索Number1_Number2Number1_Number2的组合始终是唯一的。

EG: B:S_4_0 将被替换为 B:S_5_1 ,但搜索条件为 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

我想要这些任务

  1. 如何使用字符串的后半部分找到索引或完成值
  2. 如何使用字符串的后半部分替换或删除特定值
  3. int index = Player1.IndexOf("5_6");    // Find Index
    Player1[index]="5_6";                  // Replace value
    Player1.Remove("5_6");                 // Remove 
    

    参考文献

    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

3 个答案:

答案 0 :(得分:2)

这会将B:S_4_0替换为B:S_5_1,并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

答案 1 :(得分:2)

int index = list.FindIndex(i => i.Contains("4_0"));

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

希望这会有所帮助:)

答案 2 :(得分:1)

查找索引(如果未找到则返回-1):

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

替换:

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

卸下:

list.RemoveAt(index);