tags:

views:

32

answers:

2

Hello. I have the following table structure:

Table Users

ID  | Name
1   | John
2   | Ted
3   | Alice
4   | Barney

and table UserLanguages

ID  | UserID | Language
1   | 1      | 1
2   | 1      | 5
3   | 2      | 2
4   | 2      | 3
5   | 3      | 3
6   | 4      | 4
7   | 4      | 5

I check languages 2,3 and 4 and I want to get users: 2,3,4. I want to get users who have at least something of chosen languages (or 2 or 3 or 4) How get with LINQ?

+1  A: 

Something like this should work:

var query = from u in db.Users
            join l in db.UserLanguages on u.ID equals l.UserID
            group l.Language by u into langs
            where langs.Any(l => l == 2 || l == 3 || l == 4)
            select langs.Key;

My suggestion of using predicate builder is overly complicated. IEnumerable<T>.Contains() apparently works in LINQ-to-SQL (which I didn't know). This should be much easier.

var languages = new[] { 2, 3, 4 };
var query = from u in db.Users
            join l in db.UserLanguages on u.ID equals l.UserID
            group l.Language by u into langs
            where langs.Any(l => languages.Contains(l))
            select langs.Key;
Jeff M
How can i write it, when i don't know search languages. `int[] languages = new[] { 2,3,4 }; var result = query.Where(x => x.WorkTypes.Any(y => workTypes));`
Dmitriy
I'm sorry, I don't understand what you are asking. Could you rephrase your question?
Jeff M
How build query use arrays? `.Any(x => x.ArrayOfNeedLanguages)`
Dmitriy
Thanks a lot! Searched half internet and nothing. It's so simple. Love LINQ :)
Dmitriy
A: 

You can use something like Jon Skeet suggested in your earlier question (http://stackoverflow.com/questions/3870666/how-search-linq-with-many-parametrs-in-one-column)

This should work, but it's not tested:

int[] languages = new[] {2, 3, 4};
var query = dataContext.UserLanguages
    .Where(ul => languages.Contains(ul.Language))
    .Select(ul => ul.User)
    .Distinct();
Dan Dumitru
Oh I didn't realize `IEnumerable<T>.Contains()` works in LINQ-to-SQL. Never worked for me before. :)
Jeff M
@Jeff - Yes, you have to be careful when you use it, it doesn't work for any scenario you'd expect to, I also hit a dead end with it several times. See this nice post from Rob Conery with more details: http://blog.wekeroad.com/2008/02/27/creating-in-queries-with-linq-to-sql/
Dan Dumitru
@Dan: Ah you know what, I've been using `Any()` instead and just testing for equality which is more or less semantically the same. _That_ doesn't work.
Jeff M
@Jeff - It's pretty much the same, but it's a no-go when you don't know how many elements the array will have (and the predicate builder thing works but it's indeed too complicated). "That doesn't work" - you're referring to my query?
Dan Dumitru
@Dan: Oh no, `Any()` doesn't work. ;)
Jeff M