C# 从集合中删除空字符串的方便方法
我正在寻找一种方便的方法来删除以空字符串作为其值的列表项 我知道我可以在加载到列表之前检查每个字符串是否为空C# 从集合中删除空字符串的方便方法,c#,.net,string,list,linq,C#,.net,String,List,Linq,我正在寻找一种方便的方法来删除以空字符串作为其值的列表项 我知道我可以在加载到列表之前检查每个字符串是否为空 List<string> items = new List<string>(); if (!string.IsNullOrEmpty(someString)) { items.Add(someString); } 这是我唯一的两个选择吗,也许Linq中有一些东西 谢谢您的帮助。试试: items.RemoveAll(s => string.IsN
List<string> items = new List<string>();
if (!string.IsNullOrEmpty(someString))
{
items.Add(someString);
}
这是我唯一的两个选择吗,也许Linq中有一些东西
谢谢您的帮助。试试:
items.RemoveAll(s => string.IsNullOrEmpty(s));
或者,您可以使用中的将它们过滤掉:
var noEmptyStrings = items.Where(s => !string.IsNullOrEmpty(s));
作为Darren答案的扩展,您可以使用扩展方法:
/// <summary>
/// Returns the provided collection of strings without any empty strings.
/// </summary>
/// <param name="items">The collection to filter</param>
/// <returns>The collection without any empty strings.</returns>
public static IEnumerable<string> RemoveEmpty(this IEnumerable<string> items)
{
return items.Where(i => !String.IsNullOrEmpty(i));
}
//
///返回提供的字符串集合,但不包含任何空字符串。
///
///要筛选的集合
///没有任何空字符串的集合。
公共静态IEnumerable removempty(此IEnumerable项)
{
返回items.Where(i=>!String.IsNullOrEmpty(i));
}
然后是用法:
List<string> items = new List<string>();
items.Add("Foo");
items.Add("");
items.Add("Bar");
var nonEmpty = items.RemoveEmpty();
List items=newlist();
项目。添加(“Foo”);
项目。添加(“”);
项目。添加(“栏”);
var nonEmpty=items.removempty();
在将字符串添加到列表之前检查字符串总是比从列表中删除或创建一个全新的字符串要简单。您试图避免字符串比较(实际上是检查其空值,执行速度非常快),并用列表复制来代替它,这将对应用程序的性能产生很大影响。若您只能在将字符串添加到列表之前检查字符串,那个么请这样做,不要复合。为什么您认为在添加空字符串之前检查它很麻烦?如果您正在创建此列表,那么您可以完全控制其中的内容-为什么要在事后对其进行过滤?稍后删除空元素的问题在于。删除强制将元素后面的所有元素向下复制一个索引位置。因此,对于大量字符串,最好创建一个没有这些空元素的新列表。然而,为什么这些空元素根本不应该被遗漏呢?@ChrisMcAtackney那么我最终会得到这样的结果:if(!string.IsNullOrEmpty(string1))items.Add(string1);如果(!string.IsNullOrEmpty(string2))items.Add(string2);如果(!string.IsNullOrEmpty(string3))items.Add(string3);或者我缺少一种更优雅的方式吗?使用一种方法:AddString(IList-aList,String-aString)@Jefferson这就是你的建议:我不能让列表成为类变量。在这种情况下,你甚至可以删除lambda语法,因为类型已经匹配:items.RemoveAll(String.IsNullOrEmpty)代码>很好,但如果集合的创建是由您无法控制的代码完成的呢?当然,如果他无法控制向列表中添加项目,他应该使用上面提出的方法,但请阅读我的最后一句话。此外,他说他可以在将字符串添加到列表之前检查字符串,但他不想这样做,因为这很“麻烦”。@Tarec您会使用类似的方法来代替吗:或者在添加之前有没有更优雅的方法来检查?(我不能让列表成为一个类变量)我不知道你为什么认为你的方法不好:)它很简单,干净,而且完全符合你的需要。我不记得.NET中有什么内置方法可以帮助您。如果您想让它更加优雅,并以某种方式隐藏代码,您可以为List类编写自己的扩展方法,但在我看来,这有些夸张。
/// <summary>
/// Returns the provided collection of strings without any empty strings.
/// </summary>
/// <param name="items">The collection to filter</param>
/// <returns>The collection without any empty strings.</returns>
public static IEnumerable<string> RemoveEmpty(this IEnumerable<string> items)
{
return items.Where(i => !String.IsNullOrEmpty(i));
}
List<string> items = new List<string>();
items.Add("Foo");
items.Add("");
items.Add("Bar");
var nonEmpty = items.RemoveEmpty();