[英]Remove last occurrence of string in list
是否可以使用Linq從列表中刪除最后一個字符串? 像這樣的東西:
var arr = "hello mom hello dad".Split(' ').ToList(); //hello mom hello dad
arr.RemoveLast(x => x.Contains("hello")); //hello mom dad
基本上刪除列表的最后一次出現。 我需要在字符串上使用Contains ,它必須是一個列表。
list.RemoveAt(list.FindLastIndex(x => x.Contains("hello")));
以上將刪除其中包含“hello”的最后一個字符串。 如果有可能沒有任何字符串項滿足搜索條件,並且該情況下的代碼應該什么都不做,那么它就像這樣:
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);
以下是使用列表的方法:
var arr = "hello mom hello dad".Split(' ').ToList();
arr.RemoveAt(arr.LastIndexOf("hello"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.