我有List<String>
1000 个名字。我想找出以字母“S”开头的名字的数量。
最好的选择是什么?
如果 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++;
}
使用 linq 让这一切变得简单
var count = list.Where(x => x != null && x.StartsWith("S")).Count();
如果您可以访问 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")
。)
int k = 0;
foreach (string aName in yourStringList)
{
if (aName.StartsWith("S"))
{
k++
}
}
并将k
具有以“S”开头的名称数量
List<string> list = new List<string>();
...
int count = list.Count(c => c!= null && c.StartsWith("S"));