【问题标题】:Get Count of an Item of Generic List获取通用列表项的计数
【发布时间】:2011-11-01 12:21:37
【问题描述】:

我有一个 int List<int>() 的通用列表,我想知道其中一项的计数。我该怎么做?

【问题讨论】:

  • 你能说得更具体点吗?您的List<int> 中有哪些特殊物品?

标签: c# generics c#-4.0 generic-list


【解决方案1】:

使用扩展方法是最简单的方法

int count = list.Count(i => i > 10);// get the count of those which is bigger than 10

【讨论】:

  • 成功了。但我想要这个:list.Count(i => i == 10);非常感谢你
  • @ahmadalishafiee 所以你需要的是int count = myList.Count(i => i.Equals(10));`
  • @ahmadalishafiee - Count 依赖于 using System.Linq;
【解决方案2】:

如果您想计算列表中的项目数,您可以使用表达式来执行此操作:

int count = myList.Count(i => i.Equals(5));

【讨论】:

  • Equals 是 int 上的一个方法 - 它必须是大写的 E。
【解决方案3】:

http://code.msdn.microsoft.com/LINQ-Aggregate-Operators-c51b3869

public void Linq73() 
{ 
    int[] factorsOf300 = { 2, 2, 3, 5, 5 }; 

    int uniqueFactors = factorsOf300.Distinct().Count(); 

    Console.WriteLine("There are {0} unique factors of 300.", uniqueFactors); 
}

【讨论】:

    【解决方案4】:

    通用列表的计数(从存储过程生成)

    List<GetDivisionsForGroup> GroupDivision = new List<GetDivisionsForGroup>();
            String storedProcedures = "Sp_GetDivisionsForGroup " + grpid;
            GroupDivision = db.ExecuteStoreQuery<GetDivisionsForGroup>("exec " + storedProcedures).ToList();
    
            if (GroupDivision.Count > 0)
            {
    
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-05
      • 1970-01-01
      • 2017-08-16
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      • 2015-06-25
      相关资源
      最近更新 更多