删除列表中最后一次出现的字符串

时间:2016-09-26 13:02:14

标签: c# linq

是否可以使用Linq从列表中删除最后一个字符串?像这样:

var arr = "hello mom hello dad".Split(' ').ToList(); //hello mom hello dad
arr.RemoveLast(x => x.Contains("hello")); //hello mom dad

基本上删除列表的最后一次出现。我需要在字符串上使用Contains,它必须是一个列表。

3 个答案:

答案 0 :(得分:3)

list.RemoveAt(list.FindLastIndex(x => x.Contains("hello")));

以上将删除其中包含“hello”的最后一个字符串。如果有可能没有任何字符串项满足搜索条件,并且该情况下的代码应该什么也不做,那么就像这样:

int index = list.FindLastIndex(x => x.Contains("hello"));
if (index != -1)
    list.RemoveAt(index);

答案 1 :(得分:2)

以下内容可让您确定包含" 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); 

答案 2 :(得分:-2)

以下是使用列表的方法:

var arr = "hello mom hello dad".Split(' ').ToList();
arr.RemoveAt(arr.LastIndexOf("hello"));