对象集合中,计算相同类型的个数
程序员文章站
2022-05-14 08:26:55
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