Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 删除列表中最后出现的字符串_C#_Linq - Fatal编程技术网

C# 删除列表中最后出现的字符串

C# 删除列表中最后出现的字符串,c#,linq,C#,Linq,是否可以使用Linq从列表中删除最后出现的字符串?大概是这样的: var arr = "hello mom hello dad".Split(' ').ToList(); //hello mom hello dad arr.RemoveLast(x => x.Contains("hello")); //hello mom dad int index = list.FindLastIndex(x => x.Contains("hello")); if (index != -1)

是否可以使用Linq从列表中删除最后出现的字符串?大概是这样的:

var arr = "hello mom hello dad".Split(' ').ToList(); //hello mom hello dad
arr.RemoveLast(x => x.Contains("hello")); //hello mom dad
int index = list.FindLastIndex(x => x.Contains("hello"));
if (index != -1)
    list.RemoveAt(index);

基本上删除列表的最后一个匹配项。我需要在字符串上使用,它必须是一个列表。

以下是如何使用列表:

var arr = "hello mom hello dad".Split(' ').ToList();
arr.RemoveAt(arr.LastIndexOf("hello"));
上述操作将删除其中包含“hello”的最后一个字符串。如果字符串项都不满足搜索条件,并且这种情况下的代码不应执行任何操作,则如下所示:

var arr = "hello mom hello dad".Split(' ').ToList(); //hello mom hello dad
arr.RemoveLast(x => x.Contains("hello")); //hello mom dad
int index = list.FindLastIndex(x => x.Contains("hello"));
if (index != -1)
    list.RemoveAt(index);

下面将让您确定最后一个包含“hello”的项目的索引,然后删除它(如果存在)。它使用C#6语法

var arr = "hello mom hello dad".Split(' ').ToList(); 
var removeIndex = arr.Select((s,i) => new { Value = s, Index = i })
                     .LastOrDefault(x => x.Value.Contains("hello"))
                     ?.Index;
if(removeIndex.HasValue)
    arr.RemoveAt(removeIndex.Value); 

arr
是一个数组,而不是列表。另外,这实际上还取决于您是否要从现有列表中删除或创建一个新序列,而这正是Linq实际所做的。@juharr我的错,我忘了在我的示例中添加
.ToList()
。@DmitryBychenko最后一次出现。@HenkHolterman 0元素不会删除任何内容(显然?),1元素会删除该元素“hELLO”显然与“hello”不匹配,因此不应删除。那么
“*hello*”
呢?您确实强调了
Contains()
而不是Linq,但它确实起到了作用。为什么您需要Linq呢?我不需要。此外,它不适用于Contains,我说过应该如此。@Blaatz0r因为我的“hello”和匹配的大小写并不总是等于,所以我必须检查我的输入是否包含。我需要使用ContainsWow,我从来不知道列表上有
findlastedex
。谢谢注意:如果列表中的值都不包含“hello”,则会引发异常。相反,您应该将
findlastedex
的结果分配给一个变量,并在调用
RemoveAt
@juharr之前检查-1是否存在索引自动失效异常是的。