在 C# 中从数组中查找和删除项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9375585/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 07:05:48  来源:igfitidea点击:

Find and remove items from array in c#

c#arrays

提问by Nelson T Joseph

I have a string array. I need to remove some items from that array. but I don't know the index of the items that need removing.

我有一个字符串数组。我需要从该数组中删除一些项目。但我不知道需要删除的项目的索引。

My array is : string[] arr= {" ","a","b"," ","c"," ","d"," ","e","f"," "," "}.

我的数组是: string[] arr= {" ","a","b"," ","c"," ","d"," ","e","f"," "," "}。

I need to remove the " " items. ie after removing " " my result should be arr={"a","b","c","d","e","f"}

我需要删除“”项目。即删除 " " 我的结果应该是 arr={"a","b","c","d","e","f"}

how can I do this?

我怎样才能做到这一点?

采纳答案by BlueM

  string[] arr = {" ", "a", "b", " ", "c", " ", "d", " ", "e", "f", " ", " "};
  arr = arr.Where(s => s != " ").ToArray();

回答by ?yvind Br?then

This will remove all entries that is null, empty, or just whitespaces:

这将删除所有为空、空或只是空格的条目:

arr.Where( s => !string.IsNullOrWhiteSpace(s)).ToArray();

If for some reason you only want to remove the entries with just one whitespace like in your example, you can modify it like this:

如果出于某种原因,您只想像示例中那样只删除一个空格的条目,您可以像这样修改它:

arr.Where( s => s != " ").ToArray();

回答by kamui

Using LinQ

使用 LinQ

using System.Linq;


string[] arr= {" ","a","b"," ","c"," ","d"," ","e","f"," "," "}.
arr.Where( x => !string.IsNullOrWhiteSpace(x)).ToArray();

or depending on how you are filling the array you can do it before

或者根据您如何填充阵列,您可以在此之前完成

string[] arr = stringToBeSplit.Split('/', StringSplitOptions.RemoveEmptyEntries);

then empty entries will not be put into your string array in the first place

那么空条目将不会首先放入您的字符串数组中

回答by Sunil Dhappadhule

You can use Except to remove blank value

您可以使用 except 删除空白值

string[] arr={" ","a","b"," ","c"," ","d"," ","e","f"," "," "}.
arr= arr.Except(new List<string> { string.Empty }).ToArray();