如何在AsQueryable方法中使用'Any' [英] How to use 'Any' in AsQueryable methods
问题描述
你好,
我试图让我的查询输出所有数据,如果只给出任何参数名称和价格或名称。我尝试使用'any'但它给了我 - 不能隐式地将类型'bool'转换为 - 错误。他们的另一个功能是我可以使用还是我需要调查?
提前致谢
public database_ab getData(查询查询)
{
var data = db.database_ab.AsQueryable();
if (query.name!= null )
{
data = data.Where(c = > c.Name == query.name);
}
if (query.price!= null )
{
data = data.Where(c = > c.Price == query.price);
}
return data.Any();
}
您应该将您的方法签名更改为:
public 列表< database_ab> getData(查询查询)< / database_ab >
然后将return语句更改为return data.ToList ();
您的问题是Any()返回一个bool,以查看您的集合中是否有与您的查询匹配的条目。
通过进行这些更改,您应该根据其他查询的成功和失败获得包含0个或更多条目的列表。
根据MSDN: Enumerable.Any< tsource> 确定序列是否包含任何元素。
这意味着它返回true / false(bool)值。
因此,要么更改方法签名,要么使用其他方法(即在解决方案#1中显示,或者可能是FirstOrDefault())。
- KR
Hello,
I am trying to get my query to output all data, if given any parameter name and price or name only. I tried using 'any' but it gives me -- Cannot implicitly convert type 'bool' to -- error. Is their another function i can use or do i need to look into?
Thanks in advance.
public database_ab getData(Query query)
{
var data = db.database_ab.AsQueryable();
if (query.name != null)
{
data = data.Where(c => c.Name == query.name);
}
if (query.price != null)
{
data = data.Where(c => c.Price == query.price);
}
return data.Any();
}
You should change your method signature to:
public List<database_ab> getData(Query query)</database_ab>
Then change your return statement toreturn data.ToList();
Your issue is that Any() returns a bool to see if there are any entries in your collection that match your query.
By making those changes you should get a list that contains 0 or more entries based on the success and failures of your other queries.
As per MSDN : Enumerable.Any<tsource> determines whether a sequence contains any elements.
Which means it is returning true/false (bool) value.
So either change the method signature or use other method(i.e shown in Solution #1 or may be FirstOrDefault()).
-KR
这篇关于如何在AsQueryable方法中使用'Any'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!