【问题标题】:Convenient way to drop empty strings from a collection从集合中删除空字符串的便捷方法
【发布时间】:2013-04-27 21:55:40
【问题描述】:

我正在寻找一种方便的方法来删除以空字符串为值的列表项。

我知道我可以在加载到列表之前检查每个字符串是否为空。

List<string> items = new List<string>();
if (!string.IsNullOrEmpty(someString))
{
    items.Add(someString);
}

但是,这似乎有点麻烦,特别是如果我有很多字符串要添加到列表中。

或者,我可以加载所有字符串,无论是否为空:

List<string> items = new List<string>();
items.Add("one");
items.Add("");
items.Add("two")

然后遍历列表,如果找到一个空字符串,则将其删除。

foreach (string item in items)
{
    if (string.IsNullOrEmpty(item))
    {
        items.Remove(item);
    }              
}

这是我仅有的两个选择,也许 Linq 有什么东西?

感谢您对此的任何帮助。

【问题讨论】:

  • 为什么您认为在添加之前检查空字符串很麻烦?如果您正在创建此列表,那么您可以完全控制其中的内容 - 为什么要在事后过滤它?
  • 稍后删除空元素的麻烦在于.Remove 强制复制跟随元素的所有元素向下删除一个索引位置。所以,如果有很多字符串,你最好创建一个没有那些空元素的新列表。但是,那为什么不应该把那些空元素都省略掉呢?
  • @ChrisMcAtackney 所以我会得到这样的结果: if(!string.IsNullOrEmpty(string1)) items.Add(string1); if (!string.IsNullOrEmpty(string2)) items.Add(string2); if (!string.IsNullOrEmpty(string3)) items.Add(string3);还是我错过了更优雅的方式?
  • 使用方法:AddString(IList aList, String aString)
  • @JeffRSon 这就是您的建议:pastebin.com/A5cBraQL 我无法将 List 设为类变量。

标签: c# .net string list linq


【解决方案1】:

试试:

 items.RemoveAll(s => string.IsNullOrEmpty(s));

或者您可以使用where 过滤掉它们:

var noEmptyStrings = items.Where(s => !string.IsNullOrEmpty(s));

【讨论】:

  • 在这种情况下,您甚至可以删除 lambda 语法,因为类型已经匹配:items.RemoveAll(String.IsNullOrEmpty);
【解决方案2】:

作为 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));
    }

然后用法:

        List<string> items = new List<string>();
        items.Add("Foo");
        items.Add("");
        items.Add("Bar");

        var nonEmpty = items.RemoveEmpty();

【讨论】:

    【解决方案3】:

    在将字符串添加到您的列表之前检查它们总是比从列表中删除它们或创建一个全新的字符串更容易。您正在尝试避免字符串比较(实际上检查其是否为空,执行速度非常快)并通过列表复制替换它,这将对您的应用程序的性能产生很大影响。如果您只能在将字符串添加到列表之前检查字符串 - 这样做,不要复合。

    【讨论】:

    • 很好,但是如果集合的创建是由不受您控制的代码完成的呢?
    • 当然,如果他无法控制将项目添加到列表中,他应该使用上面提出的方法,但请阅读我的最后一句话。另外 - 他说他可以在将字符串添加到列表之前检查字符串,但不想这样做,因为它“很麻烦”。
    • @Tarec 你会用这样的东西来代替:pastebin.com/A5cBraQL 还是在添加之前有更优雅的方法来检查? (我不能让 List 成为类变量)
    • 我不知道您为什么认为您的方法不好 :) 它简单、干净并且完全符合需要。我不记得 .NET 中任何可以帮助您的内置方法。如果你想让它更加优雅并以某种方式隐藏代码,你总是可以为 List 类编写自己的扩展方法,但 IMO 太夸张了。
    猜你喜欢
    • 2021-08-09
    • 2012-02-02
    • 1970-01-01
    • 2011-11-15
    • 2015-01-13
    • 2019-06-14
    • 2011-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多