【问题标题】:Equivalent of PHP array_count_values in VB.NETVB.NET 中 PHP array_count_values 的等价物
【发布时间】:2015-11-18 05:16:24
【问题描述】:

我是 VB.Net 的新手,因为我来自 PHP 开发。请问VB.NET中是否有array_count_values之类的函数。

我需要计算我的 Excel 中所有出现的项目。

【问题讨论】:

标签: vb.net


【解决方案1】:

使用 LINQ

 Dim myarray As String() = {"HP", "IBM", "HP", "HP", "MICROSOFT"} 

 Dim occur = myarray.GroupBy(Function(f) f).Select( _
                                        Function(f1) New With {.Item = f1.Key, .Count = f1.Count()})

Dim out As String
For Each itm In occur
    out = out & itm.ToString & vbCrLf
Next
MsgBox(out)

{Item = MICROSOFT, Count = 1}
{Item = HP, Count = 3}
{Item = IBM, Count = 1}

【讨论】:

    【解决方案2】:

    您可能正在寻找数组对象的Array.Length Property

    获取Array所有维度的元素总数。

    示例来自 MSDN 本身:

    using System;
    
    public class Example
    {
        public static void Main()
        {
            // Declare a single-dimensional string array
            String[] array1d = { "zero", "one", "two", "three" };
            ShowArrayInfo(array1d);
        }
    
        private static void ShowArrayInfo(Array arr)
        {
            Console.WriteLine("Length of Array:      {0,3}", arr.Length);
            Console.WriteLine("Number of Dimensions: {0,3}", arr.Rank)
            Console.WriteLine();
        }
    }
    

    输出

    // The example displays the following output:
    //       Length of Array:        4
    //       Number of Dimensions:   1
    

    【讨论】:

    • 请给我一些例子,因为页面中的例子很复杂,抱歉。
    • @Gorhell:- MSDN 中给出的示例非常清楚,并且包含 cmets,您发现哪个部分很复杂?如果您只关心计数,请查看此部分:Console.WriteLine("Length of Array: {0,3}", arr.Length);
    • @Gorhell:- 我已经为你修改了这个例子。请检查并查看
    • 这似乎不是我要找的那个。假设我有这个数组 {HP,IBM,HP,HP,MICROSOFT} 我需要输出 HP = 3 MS = 1 IBM = 1
    • @Gorhell:- 这与您提出的问题不同。等等,我会修改我的答案。
    【解决方案3】:

    试试这个:

    Dim brands() As String = New String() {"HP", "IBM", "HP", "HP", "MICROSOFT"}
            Dim result = From brand In brands
                         Group brand By brand Into brandgroup = Group
    
            For Each e In result
                Console.WriteLine("brand : {0} count : {1}", e.brand, e.brandgroup.Count)
            Next
    

    【讨论】:

    • 我对此有疑问。无法转换为事件参数
    • 将 For Each e 中的 e 替换为 result,随后 e.brand 和 e.brandgroup.Count 应该是 result.brand 和 result.brandgroup.Count
    • 知道了。另一个问题是从 System.Interops {"Exception from HRESULT: 0x800A03EC"}
    猜你喜欢
    • 2016-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-27
    • 2020-08-04
    • 2023-03-09
    • 1970-01-01
    相关资源
    最近更新 更多