开发者

LINQ Problem with Distinct count

开发者 https://www.devze.com 2023-02-17 11:17 出处:网络
Trying to understand what\'s wrong, but i really cant do it. So: return dc.dictionaries.Select( d => new AdminDictionaryViewModel

Trying to understand what's wrong, but i really cant do it. So:

return dc.dictionaries.Select(
       d => new AdminDictionaryViewModel 
       { dictionary = d,
         WordQuantity = dc.interpretations.Where(
                        i => i.iddictionary == d.iddictionary).Count() });

This works fine, but if i change to:

return dc.dictionaries.Select(
       d => new AdminDictionaryViewModel
       { dictionary = d,
         WordQuantity = dc.interpretations.Where(
                        i => i.iddictionary == d.iddictionary)
                       .Distinct(new WordsInDictionaryDistinct()).Count() });

And my class is:

public class WordsInDictionaryDistinct : IEqualityComparer<interpretation>
{
    public bool Equals(interpretation x, interpretation y)
    {
        return x.idword.Equals(y.idword) && y.idword.Equals(x.idword);
    }

    public int GetHashCode(interpretation obj)
    {
        return obj.idword.GetHashCode();
    }
}

I have:

dictionary table

iddictionary | dictionary_name

word table

idword | word_name

interpretation table

idinterpretation | iddictionary | idword

And i need to have just distinct idword in each of dictionary, bcz if i return in my first query, there could be about 10 words with idword = 15, but this is one word, not 15:

interpretation table

idinterpretation | iddictionary | idword | meaning
1                   1              1115     hello
2                   1              1115     hi
3                   1              1115     hi, bro
4                   1              1116     
5                   1              1118     good bye
6                   1              1118     bye-bye
7           开发者_运维技巧        2
8                   2

After my second query, i hope i'll get {d = 1, WordQuantity = 3}, but there is

Unsupported overload used for query operator 'Distinct'.

I've tried

.ToList<interpretation>().Distinct(new WordsInDictionaryDistinct()).Count()

but still the same error.

Really, dont know what to do :(


The problem is that the IEqualityComparer can not be translated to SQL.

Try replacing

.Distinct(new WordsInDictionaryDistinct())

with

.Select(x => x.idword).Distinct()


I think you will be better off changing your query to group instead of the way it is now, you will probably get better performance, too.

return (from d in dc.dictionaries
        join i in dc.interpretations on d.iddictionary == i.iddictionary
        group i by d into g
        select AdminDictionaryViewModel()
        {
            dictionary = g.Key,
            WorkQuantity = g.Distinct(o => o.idword).Count()
        });
0

精彩评论

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