C# 如何获取满足特定条件的列表项的数量?

C# 如何获取满足特定条件的列表项的数量?,c#,windows-phone-7,C#,Windows Phone 7,例如,我需要不是“”的列表项的数量。 ATM,我是这样解决的: public int getRealCount() { List<string> all = new List<string>(originList); int maxall = all.Count; try { for (int i = 0; i < maxall; i++)

例如,我需要不是“”的列表项的数量。 ATM,我是这样解决的:

    public int getRealCount()
    {
        List<string> all = new List<string>(originList);
        int maxall = all.Count;
        try
        {
            for (int i = 0; i < maxall; i++)
            {
                all.Remove("");
            }
        }
        catch { }
        return all.Count;
    }
public int getRealCount()
{
列表全部=新列表(原始列表);
int maxall=all.Count;
尝试
{
对于(int i=0;i
毫无疑问,性能相当差。我很幸运,这只是一个10项清单,但在电话上你应该避免这样的代码

所以我的问题是,我如何改进这段代码

一个想法是:可能已经有了一种方法。第二种方法是:所有内容只能用非“”的项目填充

我应该如何解决这个问题

谢谢

听起来像是你想要的:

return originList.Count(x => x != "");
根本不需要创建集合的副本。注意,您需要
使用System.Linq在源代码的开头使用指令

(请注意,您不应该有这样的空catch块-以这种方式抑制异常是一个糟糕的主意。只有当您想真正处理异常或想将其重新包装为另一种类型时,才捕捉异常。如果必须忽略异常,至少应该将其记录在某个位置。)

您正在调用all.remove(“”)对于列表中的每一项都是all。为什么不调用它一次呢?您的代码中根本没有使用i

为什么不:

   public int getRealCount()
   {
        List<string> all = new List<string>(originList);

       int erased =all.RemoveAll(delegate(string s)
        {
            return s == "";
        });

        return all.Count - erased;
   }
public int getRealCount()
{
列表全部=新列表(原始列表);
int erased=all.RemoveAll(委托(字符串s)
{
返回s==“”;
});
返回全部。计数-已擦除;
}
更新:


修复了我的问题。这是没有lambda的。你应该使用LINQ。安装ReSharper,它会为你生成它

另外,不要创建int maxall=all.Count,然后在for循环中使用它


对于移动应用程序,您不应该使用不必要的内存,所以只需在For循环中使用all.Count。

如果性能是您关心的问题,那么您应该保留一个仅用于这些项目的集合

如果性能不是什么大问题,我建议你对你的收藏使用Linq查询。Linq最酷的地方是搜索会延迟到你需要的时候

int nonEmptyItemCount = originList.Count(str => !string.IsNullOrEmpty(str));
你也可以这样做

int nonEmptyItemCount = originList.Count(str => str != "");

也许List的FindAll函数是最好的?尝试使用它的performanceCount返回一个int,而不是
IEnumerable