简体   繁体   English

从 Linq.Enumerable WhereListIterator 中抓取 Object

[英]Grab Object out of Linq.Enumerable WhereListIterator

im trying to grab a Object(Class) out of a List, depending on a matching string.我试图根据匹配的字符串从列表中获取对象(类)。 Im using the.Where function for the list.我使用.Where function 作为列表。 I have tried replacing it with different casts, but it always throws a InvalidCastException.我试过用不同的演员替换它,但它总是抛出一个 InvalidCastException。 Has anyone a idea how to directly cast or get the object out of the list?有谁知道如何直接将 object 排除在列表之外?

Exception: Unable to cast object of type 'System.Linq.Enumerable+WhereListIterator`1[Security.SecurityToken]' to type 'Security.SecurityToken'.例外:无法将“System.Linq.Enumerable+WhereListIterator`1[Security.SecurityToken]”类型的 object 转换为“Security.SecurityToken”类型。

public class SecurityToken {

    public string body = "example";    
}    
public class Tokenizer {

        private static List<SecurityToken> allTokens = new List<SecurityToken>();

        public static async Task<bool> isTokenValid(string token)
        {
            SecurityToken foundToken = (SecurityToken)allTokens.Where(tk => tk.body == token);
            
            return foundToken.body.equals(token);                
        } 

}

As the error message read, you are casting System.Linq.Enumerable+WhereListIterator which is the result of your query allTokens.Where(tk => tk.body == token);阅读错误消息时,您正在投射System.Linq.Enumerable+WhereListIterator这是您查询allTokens.Where(tk => tk.body == token);的结果to a SecurityToken which is wrong, a better approach is using FirstOrDefault ;对于错误的SecurityToken ,更好的方法是使用FirstOrDefault but looking at your code, all you need is to check if any item meets a condition, so I suggest using Any .但是查看您的代码,您只需要检查是否有任何项目符合条件,因此我建议使用Any

return allTokens.Any(tk => tk.body == token);

Where returns a collection not a single object. Where返回一个集合而不是单个 object。 You need to change code like below:您需要更改如下代码:

SecurityToken foundToken = allTokens
                            .Where(tk => tk.body == token)
                            .FirstOrDefault();

return (foundToken !=null); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM