Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Tuesday, March 8, 2011 6:29 AM
I am building a web application in asp.Net 4.0 and entity framework.
I am trying to retrieve a list of products based on a collection of id's.
I first gather all the id's in a collection and then pass it to the linq query. I am trying to get a functionality similar to the IN clause in SQL.
The problem seems to be with the Contains() method in the Linq to entities query.
Here is my Linq code:
public IList<Product> fn_getProductsBySubCategoryIdandBrandIDs(ArrayList alSelectedIDs)
{
IList<Product> objCProduct = null;
try
{
objDataContext = compareIndiaDataContext;
//objCProduct = objDataContext.Products.Where(db => ( (db.Product_SubCatID = iSubCategoryID) && (alSelectedIDs.Contains(db.Product_BrandID))).ToList<Product>();
objCProduct = objDataContext.Products.Where(db => alSelectedIDs.Contains(db.Product_BrandID)).ToList<Product>();
return objCProduct;
}
catch (Exception ex)
{
return objCProduct;
}
}
I got the above Linq to entities method from here: http://msdn.microsoft.com/en-us/library/bb896342.aspx
All replies (2)
Friday, April 1, 2011 4:04 AM ✅Answered
Use AsEnumerable after the 'tableName' and before applying the 'where' method.
objDataContext = compareIndiaDataContext;
objCProduct = objDataContext.Products**.AsEnumerable()**.Where(db => alSelectedIDs.Contains(db.Product_BrandID)).ToList<Product>();
return objCProduct;
Wednesday, March 9, 2011 9:16 PM
Yes, Contains can only match one condition. I suggest you trying the way:
Using List<T> and IndexOfAny method. Here's my sample:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Text.RegularExpressions;
using System.Xml.Linq;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string[] words = new string[] { "Apple","Banana","Pineapple","Age"};
//Put what you want to find into a List class
List<char> chars = new List<char>()
{
'a',
'b'
};
//Finding all words that start with a or b
var result = from w in words.AsEnumerable()
where w.ToLower().IndexOfAny(chars.ToArray()) == 0
select w;
foreach (var item in result)
{
Console.WriteLine(item);
}
}
}
}