c# 我有一个复数的对象集合,里面存放在["a","b","c","d","e","f',"g"],我想要通过一个字符串cde获取到我数组里的["c","d","e"]的元素,然后替换数组里的元素值为[1,2,3],怎么实现
时间: 2023-07-19 08:43:39 浏览: 108
您可以使用 LINQ 查询语句来实现此功能。以下是一个示例代码:
```csharp
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
List<string> list = new List<string> { "a", "b", "c", "d", "e", "f", "g" };
string str = "cde";
List<int> newValues = new List<int> { 1, 2, 3 };
var result = from s in list
let index = str.IndexOf(s)
select new { Value = s, Index = index };
foreach (var item in result)
{
if (item.Index >= 0 && item.Index + str.Length <= list.Count)
{
if (str == string.Concat(list.GetRange(item.Index, str.Length)))
{
for (int i = 0; i < str.Length; i++)
{
list[item.Index + i] = newValues[i].ToString();
}
}
}
}
foreach (var item in list)
{
Console.WriteLine(item);
}
Console.ReadLine();
}
}
```
这个代码会遍历集合中的每个元素,找到与目标字符串相同的片段,并将该片段替换为新的值。在这个示例中,新值是 [1,2,3]。最后,代码会遍历整个集合并输出每个元素。