VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 编程开发 > c#教程 >
  • C#教程之C#教程之对象集合中,计算相同类型的个数

本站最新发布   C#从入门到精通
试听地址  
https://www.xin3721.com/eschool/CSharpxin3721/

 
      /// <summary>
        ///需求:对象集合中,计算相同类型的个数

        ///思路:1,2,3,1,2,1
        ///=>    类型:1,2,3
        ///=>    数量:3,2,1
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {            
            //1、初始化集合,并赋值
            List<TestDto> inputList = new List<TestDto>();
            inputList.Add(new TestDto(1));
            inputList.Add(new TestDto(2));
            inputList.Add(new TestDto(3));
            inputList.Add(new TestDto(1));
            inputList.Add(new TestDto(2));
            inputList.Add(new TestDto(1));

            //2、挑出类型
            List<int> typeList = new List<int>();
            foreach (var item in inputList)
            {
                if (!typeList.Contains(item.Type))
                {
                    typeList.Add(item.Type);
                }
            }
            //3、对象集合
            List<TestDto> resultList = new List<TestDto>();
            foreach (var type in typeList)
            {
                TestDto testDto = new TestDto();
                testDto.Qty = 0;
                testDto.Type = type;
                resultList.Add(testDto);
            }
            //4、计算数量
            for (int i = 0; i < typeList.Count; i++)
            {
                foreach (var item in inputList)
                {
                    if (typeList[i] ==item.Type)
                    {
                        resultList[i].Qty += 1;
                    }
                }
            }
        }
复制代码

TestDto实体

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class TestDto
   {
       public TestDto()
       {
       }
 
       public TestDto(int type)
       {
           this.Type = type;
       }
 
       public int Type { getset; }
 
       public int Qty { getset; }
 
       
   }

完整代码详情请移步我的github:https://github.com/gordongaogithub/GetCountFromList


相关教程