【发布时间】:2014-06-24 20:24:54
【问题描述】:
我知道这个错误意味着什么,但我不确定如何在我的 LINQ 语句中修复它。
ScannerMessages 是一个字典。这里的值要么是来自串行扫描的数字,要么是 string.empty,要么是(在任何扫描发生之前)null。我感觉有人会说要使用 FirstorDefault(),但我不能使用 null/string.empty 的默认值。我尝试使用
.Any(x => !string.IsNullOrEmpty(x.Value)).
但这会返回一个布尔值并且是错误的检查。我觉得我需要一个 Where() 但我已经尝试过也无济于事(我也尝试过更改我的 GroupBy() 子句)。我觉得我很亲密,但我不确定在哪里修改我的表达方式。
注意:这是在锁内,所以我知道我在查询字典时没有其他线程影响字典(ScannerMessages 已锁定)
public ScanType equalMessages()
{
try
{
lock (lckObj)
{
if (_scannersPresent)
{
// Check to see if message that came through was caught in the buffer. If it has it will be equal to the previous message.
if (ScannerMessages.GroupBy(x => x.Value).Where(x => x.Count() > 1).First().Key == _holdMsg) return ScanType.ClearBuffer;
// If all messages are null or empty no scan
else if (ScannerMessages.Values.All(s => string.IsNullOrEmpty(s))) return ScanType.NoScan;
// If there is only one scanner then all scans must be determined to be either MATNUM or a rescan of an LPN
else if (_ScannerCount == 1) return ScanType.DiscernScanType;
// If distinct count of non null/empty values is less than total count of all non null/empty values, then scan is good
else if (ScannerMessages.Values.Distinct().Count(v => !string.IsNullOrEmpty(v)) < ScannerMessages.Values.Count(v => !string.IsNullOrEmpty(v)))
{
// This condition is only met if there is more than one of the same scan, and therefore is not a reprint. Pad all values with '0's for proper MATNUM format
ScannerMessages = ScannerMessages.Where(x => !string.IsNullOrEmpty(x.Value)).ToDictionary(x => x.Key, x => x.Value.PadLeft(18, '0'));
return ScanType.GoodScan;
}
// If non null/empty counts is equal to one, and the message is not the same as previous scan, then message was not from buffer and is LPN for reprint
else if ((ScannerMessages.Values.Distinct().Count(v => !string.IsNullOrEmpty(v)) == 1) && (ScannerMessages.GroupBy(x => x.Value).Where(x => x.Count() > 1).First().Key != _holdMsg)) return ScanType.Reprint;
else return ScanType.NoScan;
}
return ScanType.NoScan;
}
}
catch (Exception ex) {
myEvents.raiseErrorMessageBox(ex.Message);
throw new Exception(ex.Message, ex); }
}
编辑:我不确定哪一行抛出错误-我认为它要么是第一个 if 行 要么 最后一个 else if 在 else 返回 ScanType.NoScan 之前。这些是使用 First() 调用的唯一语句。问题是大约每半秒调用一次,因此调试它会备份。有 3 个线程访问 ScannerMessages 字典,然后调用它的线程检查该字典。当我有 4 个线程访问它时,我不确定如何调试它。我唯一知道的是它是*线程安全的:/如果我尝试在第一行放置一个断点,它会命中很多次,以至于当我单步执行时,我会错过任何“真实”扫描。
【问题讨论】:
-
哪一行报错?
-
@Blorgbeard 我在我认为问题发生的地方添加了 - 评论回复太长了。
-
FWIW,如果我理解 FirstOrDefault() 它将获取 string.empty|null。我需要的是获取 First().Key.Where(x => !string.IsNullOrEmpty(x.Value) 但这也不起作用。例如字典可能是 , , 。根据我对我的陈述的理解,它会抛出这个错误,但我又不能做 First() 或 FirstOrDefault()