【问题标题】:delete empty entries tuple List String [closed]删除空条目元组列表字符串[关闭]
【发布时间】:2020-10-26 19:02:17
【问题描述】:

我有一个包含 5 个字符串值的元组列表。此列表包含大约 250 个条目,其中有许多空条目。 如何删除这些空条目?

 var program_list = new List<Tuple<string, string, string, string, string>>();
 program_list.Add(Tuple.Create(program_name_String, publisher_name_String, program_version_String, install_location_String, uninstall_location_String));

我知道如何使用单个字符串列表删除这些空条目。但此代码不再适用于元组列表。

program_names = program_names.Where(s => !string.IsNullOrWhiteSpace(s)).Distinct().ToList();
program_names = program_names.Where(s => !string.IsNullOrEmpty(s)).Distinct().ToList();
program_names.Sort();

非常感谢。

【问题讨论】:

  • 您想确切过滤掉哪些条目?那些所有5个字符串都是空的?那些五个字符串中至少有一个是空的?那些五个字符串(程序名称)中的第一个是空的? (提示:最后一个最容易实现。在我们为您破坏这个难题之前,您想尝试一下吗?)
  • 恕我直言,创建一个新类并将它们放入List&lt;Apps&gt;...此时您的工作要容易得多。另外,似乎在将它们添加到列表之前,为什么不检查字符串?

标签: c# list tuples


【解决方案1】:

我建议使用类而不是元组。此外,您仍然可以像将它用于字符串列表一样使用它。你只需要让它知道更深入。将 s 替换为 s.Item1 即可。

program_names = program_names.Where(s => !string.IsNullOrWhiteSpace(s.Item1)).Distinct().ToList();

但我建议这样做:

    public class myProgramClass
    {
        public string name, publisher_name, version, install_location, uninstall_location;
    }

    List<myProgramClass> program_list = new List<myProgramClass>();

    myProgramClass new_entry = new myProgramClass() { name = "Name", publisher_name = "pub Name", version = "1.02", install_location = "dir", uninstall_location = "" };
    program_list.Add(new_entry);

    program_list = program_list.Where(s => string.IsNullOrWhiteSpace(s.name)).Distinct().ToList();

【讨论】:

    猜你喜欢
    • 2014-02-18
    • 1970-01-01
    • 2011-04-20
    • 2014-06-19
    • 1970-01-01
    • 2011-07-28
    • 2014-05-14
    • 2023-03-25
    • 1970-01-01
    相关资源
    最近更新 更多