views:

25

answers:

1

Hello All, 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!)

A: 

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();
Jonathan Bates
Yes, I have 5 entries in the db. 5 people ranging in ages from 39 to 41. I can't seem to get your syntax to function either.
CraigF
In your example, the a in the lambda expression would be an int, which doesn't have a "Contains" definition
CraigF
Sorry, must learn to finish the coffee before posting on SOI spiked this and it works for me 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();So are you sure you are connecting to the DB and the resultant tables?
Jonathan Bates
Weird.. I put this into visual studio in a new project and it worked... LinqPad still returns nothing, and my real project which is slightly more complicated returns nothing...
CraigF
Edit your answer so it works and I'll mark this one answered (still need to know why the more complex one doesn't work.. (maybe I should post that on here?)
CraigF