TestDto實體 完整代碼詳情請移步我的github:https://github.com/gordongaogithub/GetCountFromList ...
/// <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實體
public class TestDto { public TestDto() { } public TestDto(int type) { this.Type = type; } public int Type { get; set; } public int Qty { get; set; } }
完整代碼詳情請移步我的github:https://github.com/gordongaogithub/GetCountFromList