James
James

Reputation: 41

LINQ & Lambda Expressions equivalent of SQL In

Is there a lambda equivalent of IN? I will like to select all the funds with ids either 4, 5 or 6. One way of writing it is:

List fundHistoricalPrices = lionContext.FundHistoricalPrices.Where(fhp => fhp.Fund.FundId == 5 || fhp.Fund.FundId == 6 || fhp.Fund.FundId == 7).ToList();

However, that quickly becomes unmanageable if I need it to match say 100 different fundIds. Can I do something like:

List fundHistoricalPrices = lionContext.FundHistoricalPrices.Where(fhp => fhp.Fund.FundId in(5,6,7)).ToList();

Upvotes: 3

Views: 2086

Answers (4)

Jan
Jan

Reputation: 16032

No, the only similar operator i'm aware of is the Contains() function.

ANother was is to construct your query dynamically by using the predicate builder out of the LINQkit: http://www.albahari.com/nutshell/predicatebuilder.aspx

Example

int[] fundIds = new int[] { 5,6,7};

var predicate = PredicateBuilder.False<FundHistoricalPrice>();

foreach (int  id in fundIds)
{
    int tmp = id;
    predicate = predicate.Or (fhp => fhp.Fund.FundId == tmp);
}

var query = lionContext.FundHistoricalPrices.Where (predicate);

Upvotes: 0

Romain Meresse
Romain Meresse

Reputation: 3044

You could write an extension method like this :

public static bool In<T>(this T source, params T[] list)
{
  if(null==source) throw new ArgumentNullException("source");
  return list.Contains(source);
}

Then :

List fundHistoricalPrices = lionContext.FundHistoricalPrices.Where(fhp => fhp.Fund.FundId.In(5,6,7)).ToList();

Upvotes: 0

Peter Perh&#225;č
Peter Perh&#225;č

Reputation: 20782

It's somewhere along these lines, but I can't quite agree with the approach you have taken. But this will do if you really want to do this:

.Where(fhp => new List<int>{5,6,7}.Contains( fhp.Fund.FundId )).ToList();

You may want to construct the List of ids before your LINQ query...

Upvotes: 1

Dave D
Dave D

Reputation: 8972

You can use the Contains() method on a collection to get the equivalent to in.

var fundIds = new [] { 5, 6, 7 };

var fundHistoricalPrices = lionContext.FundHistoricalPrices.Where(fhp => fundIds.Contains(fhp.Fund.FundId)).ToList();

Upvotes: 0

Related Questions