如何在linq的where子句中使用Contains [英] how to use Contains in where clause in linq
问题描述
我有这个:
var myResult = uow.GetRepository<SLItemsCustomersCard, long>()
.Query(x => x.CustomerId == customerId && x.SquareColor == squareColor)
.OrderBy(x => x.BranchMapRang)
.Select((r, i) => new { Row = r, Index = i })
.Where(x => x.Index == visitCounter - 1).ToList();
但是我想在where子句中实现这一点:
but I want to achive this in where clause:
.Where(x => x.Index.Cotains(visitCounter)).ToList();
该怎么做?
推荐答案
您似乎误解了Contains
方法的作用.我将此答案基于您之前的用法:
You seem to be misunderstanding what the Contains
method does. I'm basing this answer on your earlier usage of:
Where(x => x.Index == visitCounter - 1)
换句话说,visitCounter
是整数(Index
也是).但是然后您要像这样使用它:
In other words, visitCounter
is an integer (and so is Index
). But then you want to use it like this:
Where(x => x.Index.Contains(visitCounter))
这在语法上没有意义.整数(Index
)没有Contains
函数.对我来说,您要达到的目标尚不完全清楚,但您的评论进一步阐明了这一点:
Which does not make syntactical sense. An integer (Index
) does not have a Contains
function. It's not fully clear to me what you are trying to achieve, but your comment clarifies it a bit more:
但是我想在SQL Server中实现类似IN子句的功能.
But I want to achieve something like IN clause in SQL server.
SQL中的IN
子句需要一定范围的可能性(对于您的情况,为整数列表),并且您在此处不使用整数列表.此外,您将其用Index.Contains(visitCounter)
表示,这意味着您希望Index
是整数列表?
The IN
clause in SQL requires a range of possibilities (a list of integers, in your case), and you're not working with a list of integers here. Furthermore, you have phrased it as Index.Contains(visitCounter)
which would imply that you're expecting Index
to be the list of integers?
那根本没有道理.因此,假设您对伪代码不正确,我将为您提供最有意义的答案:
That simply doesn't make sense. So I'll give you the answer that makes the most sense, on the assumption that you weren't accurate with your pseudocode:
List<int> visitorIds = new List<int>() { 1, 5, 99, 125 };
然后您可以执行以下操作:
And then you can do the following:
.Where(x => visitorIds.Contains(x.Index))
简而言之,该代码段告诉计算机仅给出在visitorIds
列表中提到Index
的项目".
To put it in words, this snippet basically tells the computer to "only give the items whose Index
is mentioned in the visitorIds
list".
这篇关于如何在linq的where子句中使用Contains的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!