【问题标题】:number of variables in list generic泛型列表中的变量数
【发布时间】:2013-09-21 11:05:19
【问题描述】:

我想知道 List 泛型中哪个方法(如果有)指示对象的数量是否满足特定要求,例如:

List<string> example = new List<string>();

if (example."put the method here" = 0)
{
    Console.WriteLine("There are no objects in this list");
}
else if (example."put method here" > 0)
{
    Console.WriteLine("This list contains objects");

在示例代码中,我想知道该列表是否包含 0 个对象,然后控制台写入特定文本,如果列表包含超过 0 个项目/对象,则控制台写入另一个文本。

【问题讨论】:

  • 请添加您正在使用的语言(我猜是 C#)

标签: c# list generics methods


【解决方案1】:

如果您不想查看 List 中的任何项目,则只需使用 Count(假设 C# 是语言)。以下是您的代码:

List<string> example = new List<string>();

if (example.Count == 0)
{
    Console.WriteLine("There are no objects in this list");
}
else if (example.Count > 0)
{
    Console.WriteLine("This list contains objects");
}

如果您需要获取符合特定要求的项目,请使用Enumerable.Count

例如,如果您需要以字符串“The”开头的所有项目的计数,那么您可以使用

int count = example.Count(i => i.StartsWith("The") == true)

【讨论】:

    【解决方案2】:

    您可以使用 Any() 而不是使用 Count() == 0,它可以让您免于输入几个字符!然后可以将“else if”更改为“else”。

    【讨论】:

      猜你喜欢
      • 2017-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-19
      相关资源
      最近更新 更多