从数组中删除空元素 [英] Removing empty elements from an array
本文介绍了从数组中删除空元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你好
我有
string [] myArray = new [] {1, 2,3,};
如何将myArray转换/格式化为
string [] myArray = new [] {1,2,3};
在其他作品中,我如何以编程方式删除最后一个空条目
我假设我不知道空条目的索引。
提前致谢
Martin
Hi there
I Have
string[] myArray=new []{"1","2","3",""};
How can i convert/Format myArray to Look Like
string[] myArray=new []{"1","2","3"};
In other works, how can i programmatically remove the last empty entry
I am assuming that i don't know the index of the empty entry.
Thanks in advance
Martin
推荐答案
你可以轻松简单地完成这个工作
myArray = myArray.Where(x =>!string.IsNullOrEmpty(x )。ToArray();
you can do this easy ans simple way
myArray = myArray.Where(x => !string.IsNullOrEmpty(x)).ToArray();
C#没有直接的方法,但是......你可以尝试:
C# doesn'ty have a direct way to do that, but... you could try:
string[] x = new string[] { "1", "", "2", "", "3", "4" };
List<string> y = x.ToList<string>();
y.RemoveAll(p => string.IsNullOrEmpty(p));
x = y.ToArray()
我建议你检查你的设计,考虑到从中删除或插入元素的固有成本/进入数组。这与创建全新阵列并制作所有数据的副本相同。性能可能会受到太大影响。使用列表作为临时对象无法解决问题。
因此,请考虑首先使用容器。您可以使用,例如System.Collections.Generic.List<>
,请参阅 http://msdn.microsoft.com/en-us/library/system.collections.generic.aspx [ ^ ]。
-SA
I would advise you to review your design taking into account the inherent cost of removal or insertion of an element from/into the array. This is the same as creation of a brand new array and making a copy of all data. The performance can suffer too much. Using a list as a temporary object won't solve the problem.
So, consider using containers in first place. You can use, saySystem.Collections.Generic.List<>
, please see http://msdn.microsoft.com/en-us/library/system.collections.generic.aspx[^].
—SA
这篇关于从数组中删除空元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文