0

I have to query a repository where column a = {myvalue} and column b has any value in a collection.

Here's what I have:

Application[] applicationCollection = GetAllApplications();
var result = repo.GetAll(r => r.Email == myEmail && r.Application.In(applicationCollection));

I can't figure out how to write the "in" part...

Preferrably links to how to do this would be best, so I can learn it, as opposed to just getting the answer :). Thanks all.

(I'm sure this is a repeat question, but my Google/search skills are obviously poor.)

ganders
  • 7,285
  • 17
  • 66
  • 114
  • Are you saying that you know when `applicationCollection` *contains* `r.Application`? – Gabe Jul 15 '13 at 22:40

4 Answers4

1

The SQL idea of item in collection is written in C# (including LINQ) as collection.Contains(item). In your example, this might be:

var result = repo.GetAll(r => r.Email == myEmail &&
               applicationCollection.Contains(r.Application));
Tim S.
  • 55,448
  • 7
  • 96
  • 122
  • If it's as easy as this, I feel extremely stupid. Will try when I get back to work tomorrow, thanks. – ganders Jul 15 '13 at 22:47
0
ApplicationCollection.Contains(r.Application)
Steve0
  • 2,233
  • 2
  • 13
  • 22
0

Use .Contains(collection) instead of in. Here's a link since you wanted one.

Community
  • 1
  • 1
TOlsen
  • 45
  • 1
  • 2
  • 8
0

If you want to write it the way you've shown, you can write this extension method:

public static bool In<T>(this T item, IEnumerable<T> set)
{
    return set.Contains(item);
}

And then use it exactly like you did in your question:

Application[] applicationCollection = GetAllApplications();
var result = repo.GetAll(r =>
    r.Email == myEmail &&
    r.Application.In(applicationCollection));

This will work fine if you're only working with in-memory sets. If you're doing something like LINQ-to-SQL, however, this won't be compatible.

Note: I'm not trying to imply that this extension method might be a good idea to use - I'm just saying it's possible to write one like that.

Timothy Shields
  • 75,459
  • 18
  • 120
  • 173