无法在LINQ扩展方法中使用==

无法在LINQ扩展方法中使用==,linq,Linq,我有以下结构,它是我字典的关键: public struct CodeAttribute { public int ProcessorId; public Enums.TransactionType transactionType; public string ErrorMessage; } 我现在得到了以下一个值,因为它只是一个示例: var errors = new Dictionary<CodeAttribute, int> { {CreateCod

我有以下结构,它是我字典的关键:

public struct CodeAttribute
{
   public int ProcessorId;
   public Enums.TransactionType transactionType;
   public string ErrorMessage; 
}
我现在得到了以下一个值,因为它只是一个示例:

var errors = new Dictionary<CodeAttribute, int>
{
   {CreateCodeAttributeList(2, Enums.TransactionType.Order, "Invalid ProcessorId sent in the Payment Request"), 100 }
};
更新

在山姆的帮助下,我想这可能会奏效

CodeAttribute codeAttribute = errorsList.FirstOrDefault(e => e.Key.ProcessorId ==
_processorId && e.Key.transactionType == _transactionType
             && e.Value == errorCode).Key;

如果我理解正确,那么你想要

var codeAttribute = errorsList.FirstOrDefault(e => 
                                                e.Key.ProcessorId == _processorId
                                             && e.Key.transactionType == _transactionType
                                             && e.Value == errorCode);

    if(codeAttribute == null)
    {
      //no item matches in the dictionary.
    }

return codeAttribute.Key.ErrorMessage;
请注意,codeAttribute将是一个KeyValuePair,因此您需要codeAttribute.Key.ErrorMessage作为返回值

您不需要使用Where,因为它将返回一个IEnumerable,所以如果您想要一个项目,这将不起作用


您可能需要这样做:

CodeAttribute codeAttribute = errorsList.FirstOrDefault(e => e.Key.ProcessorId == _processorId && e.Key.transactionType ==_transactionType)
var errorMessage = errorsList
       .Where(e => e.Key.ProcessorId == _processorId
                   && e.Key.transactionType == _transactionType
                   && e.Value == errorCode)
       .Select(e => e.Key.ErrorMessage)
       .FirstOrDefault();

虽然其他答案是正确的,但我可能会这样写:

CodeAttribute codeAttribute = errorsList.FirstOrDefault(e => e.Key.ProcessorId == _processorId && e.Key.transactionType ==_transactionType)
var errorMessage = errorsList
       .Where(e => e.Key.ProcessorId == _processorId
                   && e.Key.transactionType == _transactionType
                   && e.Value == errorCode)
       .Select(e => e.Key.ErrorMessage)
       .FirstOrDefault();
也就是说,在前面推送条件进行筛选,从该结果集中选择我想要的数据,然后在转换后的数据存在时获取第一个结果

由于IEnumerable查询是惰性的,因此在第一个成功过滤的对象上仍然会停止


因为来源是一本字典,设置相关的Equals/GetHashCode并构造代码以供使用可能也是谨慎的做法。

您会得到什么错误?where子句返回IEnumerable而不是单值where e=>e.Key.transactionType===\U transactionType==errorCode应该是什么意思?我得到的错误是它不喜欢==运算符,表示它无法在本例中使用我在此处尝试使用的方法来应用它。linq语句末尾的.Key将起作用,但如果没有与搜索条件匹配的项目,则将获得NullReferenceException。否则,您可以执行空检查以捕获此情况。是。。第一个或默认值将采用返回布尔值的函数。你也可以在Where中使用&&如果你想要一个IEnumerable返回,你不需要使用两个单独的Where,因为你将返回一个KeyValuePair而不是CodeAttributeright,我没有注意到,他应该使用var result=blah;然后从中提取关键点和值,创建他想要的对象。