6

我有List<String>1000 个名字。我想找出以字母“S”开头的名字的数量。

最好的选择是什么?

4

5 回答 5

12

如果 Linq 可用

using System.Linq;
list.Where(s=>s!=null && s.StartsWith("S")).Count();

如果 Linq 不可用。

int count=0;
foreach (string s in list) {
  if (s!=null && s.StartsWith("S")) count++;
}
于 2012-10-16T09:56:18.120 回答
3

使用 linq 让这一切变得简单

var count = list.Where(x => x != null && x.StartsWith("S")).Count();
于 2012-10-16T09:54:18.403 回答
1

如果您可以访问 LINQ,例如

int count = myList.Count(name => name.StartsWith("S"));

否则,类似

int count = myList.FindAll(name => name.StartsWith("S")).Count;

(编辑:正如 Bob Vale 在他的回答中指出的那样,如果您的任何列表条目可能为空,您需要添加一个空检查,例如name => name != null && name.StartsWith("S")。)

于 2012-10-16T09:54:59.037 回答
1
int k = 0;
foreach (string aName in yourStringList)
{
  if (aName.StartsWith("S"))
    {
    k++
    }
}

并将k具有以“S”开头的名称数量

于 2012-10-16T09:57:21.223 回答
0
List<string> list = new List<string>();
...
int count = list.Count(c =>  c!= null && c.StartsWith("S"));
于 2012-10-16T09:56:39.703 回答