【问题标题】:grouping and counting objects based on property根据属性对对象进行分组和计数
【发布时间】:2009-06-18 22:28:50
【问题描述】:

我需要迭代一个对象集合。基于对象的属性值,我需要将对象组合在一起。我还需要每个离散属性值的总数。我不知道会有多少组,每个组中可能有 1 到 n 个对象。

我该怎么做?有没有可以帮助我解决这个问题的算法?伪代码或引用都可以。

非常感谢!

【问题讨论】:

    标签: .net vb.net visual-studio-2008


    【解决方案1】:

    【讨论】:

      【解决方案2】:

      这里有一些可能对您有所帮助的代码。它通过属性 A 将 Target 实例分组,然后迭代分组并打印组的计数...

      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Text;
      
      namespace IterateCollection
      {
          class Program
          {
              static void Main(string[] args)
              {
                  var lst = new List<Target>() { new Target() { A=1, B=1 },
                                                 new Target() { A=1, B=2 },
                                                 new Target() { A=2, B=1 },
                                                 new Target() { A=2, B=2 },
                                                 new Target() { A=3, B=1 } };
      
                  var grp = lst.GroupBy(t => t.A);
                  var dic = grp.ToDictionary(g => g.Key);
      
                  List<int> res = null;
      
                  foreach (var key in dic.Keys )
                  {
                      res = dic[key].Select(t => t.A).ToList();
      
                      Console.WriteLine("Number of {0} is {1}", key, res.Count);
                  }
      
      
                  Console.ReadLine();
              }
          }
      
          public class Target
          {
              public int A { get; set; }
              public int B { get; set; }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-23
        • 2015-06-17
        • 2019-02-11
        • 1970-01-01
        • 2020-12-05
        相关资源
        最近更新 更多