我有一个使用此类的通用列表
public class Data
{
public string Date { get; set; }
public int OkRecords { get; set; }
public int ErrorRecords { get; set; }
}
我还有List<string>
,其中包含唯一的日期。我需要添加原始列表的数据,使得日期应该只有一个记录,即如果有10个唯一日期,则应该只有10个记录从原始列表中过滤掉。我已经实现了以下逻辑,但如果数据超过10万,则会占用太多时间。
int distinctDatesCount = distinctDates.Count;
for (int i = 0; i < distinctDatesCount; i++)
{
string date = distinctDates[i];
int ok = 0, error = 0;
foreach (var item in dataList.Where(w => w.Date == date))
{
ok += item.OkRecords;
error += item.ErrorRecords;
}
Data dataValues = new Data
{
Date = date,
OkRecords = ok,
ErrorRecords = error
};
DataListCombined.Add(dataValues);
}
DataListCombined是我存储新合并数据的列表。
我已将日期保存为字符串格式,因为我在其他地方使用字符串格式需要它。
答案 0 :(得分:1)
您可以使用Linq GroupBy
按日期对数据进行分组,然后使用Sum
将计数添加到单个对象中。
var DataListCombined = dataList.GroupBy(data => data.Date)
.Select(groupedData =>
new Data {
Date = groupedData.Key,
OkRecords = groupedData.Sum(item => item.OkRecords),
ErrorRecords = groupedData.Sum(item => item.ErrorRecords)
})
.Where(data => distinctDates.Contains(data.Date))
.ToList();
您还可以查看此资源以获取更多示例。
答案 1 :(得分:1)
我个人使用了团体加入。因为DataList中的记录不应该在最终结果中。
public class Data
{
public string Date { get; set; }
public int OkRecords { get; set; }
public int ErrorRecords { get; set; }
}
class Program
{
static void Main(string[] args)
{
Random rand = new Random();
List<string> distinctDates = new List<string>();
for (int i = 0; i < 10000; i++)
{
distinctDates.Add( rand.Next(1, 12) + "/" + rand.Next(1, 30) + "/1");
}
List<Data> dataList = new List<Data>();
for (int i = 0; i < 10000; i++)
{
dataList.Add(new Data{ Date = rand.Next(1,12)+"/"+rand.Next(1, 30)+"/1", OkRecords=0, ErrorRecords=1});
}
Stopwatch watch = new Stopwatch();
watch.Start();
Method1(distinctDates, dataList);
watch.Stop();
Console.WriteLine(watch.Elapsed);
watch.Reset();
watch.Start();
Method2(distinctDates, dataList);
watch.Stop();
Console.WriteLine(watch.Elapsed);
Console.ReadLine();
}
private static void Method1(List<string> distinctDates, List<Data> dataList)
{
List<Data> DataListCombined = new List<Data>();
int distinctDatesCount = distinctDates.Count;
for (int i = 0; i < distinctDatesCount; i++)
{
string date = distinctDates[i];
int ok = 0, error = 0;
foreach (var item in dataList.Where(w => w.Date == date))
{
ok += item.OkRecords;
error += item.ErrorRecords;
}
Data dataValues = new Data
{
Date = date,
OkRecords = ok,
ErrorRecords = error
};
DataListCombined.Add(dataValues);
}
}
private static void Method2(List<string> distinctDates, List<Data> dataList)
{
List<Data> DataListCombined = distinctDates.GroupJoin(
dataList,
distinctDateItem => distinctDateItem,
dataListItem => dataListItem.Date,
(dataListItem, distinctDateItems) => new Data
{
ErrorRecords = distinctDateItems.Sum(item => item.ErrorRecords),
OkRecords = distinctDateItems.Sum(item => item.OkRecords),
Date = dataListItem
}
).ToList();
}
}