Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

c# - how to use Contains in where clause in linq

I have this:

        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();

but I want to achive this in where clause:

.Where(x => x.Index.Cotains(visitCounter)).ToList();

How to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

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))

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:

But I want to achieve something like IN clause in SQL server.

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))

To put it in words, this snippet basically tells the computer to "only give the items whose Index is mentioned in the visitorIds list".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...