【发布时间】:2020-08-14 10:59:46
【问题描述】:
'Value to add was out of range. (Parameter 'value')'.
我在使用 Nuget 的 TDMSReader 时遇到了 ToList 和 IEnumerable 的问题。 我试图遍历 IEnumerable 并添加到新列表,但主要错误来自 ForEach 循环。我也试过 ToList,它给出了同样的错误。
在进入下一个“项目”之前,我无法读取引发错误的值,因为它发生在 foreach 循环中。从我发现的所有内容来看,这可能是 DateTime 最小/最大错误,但我在数据中找不到错误,并尝试删除 2000 年到 2021 年之间的任何日期。我最多可以在“da”中获得 2961 条记录在抛出错误之前。不过,“频道”中有 6204 条记录。
using LambdaTdms.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TdmsMaster.Managers
{
public class StackOverflow
{
public void Main()
{
string basePath = Functions.GetBasePath();
string filePath = Functions.GetNewFilePath(basePath);
if (filePath == null)
{
return;
}
using (NationalInstruments.Tdms.File file = new NationalInstruments.Tdms.File(filePath))
{
try
{
file.Open();
List<PutObjectResponseModel> models = ByChannel(file);
file.Dispose();
}
catch (Exception ex)
{
//Error handling
}
}
}
private List<PutObjectResponseModel> ByChannel(NationalInstruments.Tdms.File file)
{
List<PutObjectResponseModel> responseModels = new List<PutObjectResponseModel>();
foreach (var group in file.Groups)
{
foreach (NationalInstruments.Tdms.Channel channel in group.Value)
{
string fileName = $"{FormatPath(group.Key)}_{ FormatPath(channel.Name)}";
IEnumerable<DateTime> datas = channel.GetData<DateTime>();
//Error: datas.ToList();
List<DateTime> da = new List<DateTime>();
try
{
datas = datas.OrderBy(c => c.Year)
.ThenBy(c => c.Month)
.ThenBy(c => c.Day)
.ThenBy(c => c.Hour)
.ThenBy(c => c.Minute)
.ThenBy(c => c.Second)
.ThenBy(c => c.Millisecond);
datas = datas.Where(p => p.Year > 2000).Where(p => p.Year < 2021);
//Error: foreach (DateTime item in datas)
foreach (DateTime item in datas)
{
DateTime dt = (DateTime)item;
if (dt == null)
{
Console.WriteLine(item);
}
else
{
da.Add(item);
}
}
}
catch
{
//handler error thrown from *foreach (DateTime item in datas)
}
}
}
return responseModels;
}
private string FormatPath(string path)
{
path = path.Replace("/", " ").Replace("?", "").Replace("*", "");
return path;
}
}
}
【问题讨论】: