假设有一个string列表lstTemp,包含的数据为:
2021-01-01
2021-01-01
2021-02-01
2021-03-01
2021-03-01
2021-03-01
想要实现如下效果
2021-01-01 记录数:2
2021-02-01 记录数:1
2021-03-01 记录数:3
1 将原始列表中数据消除重复后送入临时列表
2 循环临时列表,在原始列表中查找临时列表中每项的个数
3 将临时列表中的每项以及每项的个数送入结果列表
如下语句用于实现这个效果:
using System.Collections.Generic;
using System.Linq;
using System;
片段
List lstTemp = new List();
lstTemp.Add(“2021-01-01”);
lstTemp.Add(“2021-01-01”);
lstTemp.Add(“2021-02-01”);
lstTemp.Add(“2021-03-01”);
lstTemp.Add(“2021-03-01”);
lstTemp.Add(“2021-03-01”);
List<string> lstAlien = new List<string>();
if (lstTemp.Count != 0)
{
List<string> lstdistinct = lstTemp.Distinct().ToList();
foreach (string strT in lstdistinct)
{
List<string> lstFind = lstTemp.FindAll(delegate (string s)
{
return s == strT;
});
lstAlien.Add(strT + " 记录数: " + lstFind.Count.ToString());
}
}
foreach (string strT in lstAlien)
{
Console.WriteLine(strT);
}
输出结果为:
2021-01-01 记录数: 2
2021-02-01 记录数: 1
2021-03-01 记录数: 3