开发者

LinqtoSQL with a where clause containing a List?

I have researched this to death. There does seem to be some answers here already, but frankly the answers confuse me. So I'll try to make this as basic as possible.

If I have a table in a database, "People" with a name column(string) and an age(int) column. Then I do something like this:

List<int> ages = new List<int>();
ages.Add(39);
ages.Add(40);
var result = from p in People
where ages.Contains((int)p.Age)
select p;

The syntax is passing, but returns nothing (both in VS2010 and LinqPad). Shouldn't this make a SQL statement with a where clause containing the ages in my list?

Simple answer anyone? (Ideally if you could modify my example and make it work..开发者_运维百科 that would be great!)


if you are doing it as Linq2SQL, it appears you are doing it correctly in order to ensure the proper projections for SQL Server. You may try writing it a slightly different way, like:

var result = from p in People
where ages.Select(a => a).Contains(p.Age)
select p;

You say that it returns nothing. Are you sure that there are matching records to return? Also, are you using result anywhere? The query won't execute if you don't bind it to something or call ToList() to some other projecting interaction.

Sample from comments:

var ints = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

var Merchandiser = (new DataClasses1DataContext()).Merchandisers;

var result = from m in Merchandiser 
where ints.Contains(m.Id) 
select m; 

foreach (var item in result) 
{ 
   Console.WriteLine(item.Name); 
} 

Console.ReadLine();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜