在 LinQ 中应用Where 和 Take 时出现问题
我有一个 List
,我想对其应用 Take 和Where 条件,但它不起作用,我想知道问题是什么。我的查询是
List<MediaRef> objmed = new List<MediaRef>();
objmed = GetRecords(); //GetRecords will fetch records
objmed.Where(e => e.Title.Contains(Keyword)) //This line is not working
Where条件不起作用,但是当我将其更改为
List<MediaRef> objmed = new List<MediaRef>();
objmed = GetRecords();
objmed = (from p in objmed
where p.Title.Contains(Keyword)
select p).ToList();
它时工作正常。我使用 Take()
函数面临同样的问题。可能是什么问题?
I have a List<MediaRef>
and i want to apply Take and Where condition on it but it is not working i wonder what is the issue. My query is
List<MediaRef> objmed = new List<MediaRef>();
objmed = GetRecords(); //GetRecords will fetch records
objmed.Where(e => e.Title.Contains(Keyword)) //This line is not working
and Where condition is not working but when i change this to
List<MediaRef> objmed = new List<MediaRef>();
objmed = GetRecords();
objmed = (from p in objmed
where p.Title.Contains(Keyword)
select p).ToList();
It works fine. I am facing same problem using Take()
function. What may be the problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
你需要分配结果,
Were
运算符不会更改源集合,它创建一个惰性输出集合。当您枚举
Where
的结果时,它将读取源集合并返回符合条件的元素。在您的工作示例中,您 (1) 分配结果,(2) 使用ToList
强制枚举。尝试:
You need to assign the result, the
Were
operator doesn't change the source collection, it creates a lazy output collection.When you enumerate the result of
Where
it will read the source collection and return the elements that match the condition. In your working example you are (1) assigning the result, and (2) usingToList
to force enumeration.Try:
试试这个:
您忘记将 where 的结果分配给某物。
Try this:
You forgot to assign the result of where to something.
试试这个...
如果您要使用
foreach
枚举列表,则不需要ToList()
。Try this...
The
ToList()
is unnecessary if you are going to enumerate the list withforeach
.您需要将 where 的输出分配给新变量 - 例如
,或者,当然您可以使用流体样式:
You need to assign the output of where to a new variable - e.g.
or, of course you can use fluid styling:
你想达到什么目的? .Where 和 .Take 方法根据给定的条件返回对象列表。
代码应该是:
What are you trying to achieve? The .Where and .Take methods return a list of objects depending on the criteria given.
The code should be: