当前位置: 动力学知识库 > 问答 > 编程问答 >

Odd Results with LINQ Query in C#

问题描述:

This is my current LINQ query:

 var model =

db.RPTINQUIRies

.Where(t => t.CONNAME.StartsWith(term))

.Take(25)

.Select(t => new

{

label = t.CONNAME

}).Distinct();

CONNAME refers to a contact name, say "Andy Smith". I am selecting distinct as there could be 100 rows with "Andy Smith" in.

Lets say some of the distinct names I have are as follows:

  • Andy Smith
  • Andy Bloggs
  • Andy Dawes
  • Andy Sutton

If I pass the term "Andy" into the query I would expect to see the list as above, but it does not generate all of them. It may generate Andy Smith, Andy Bloggs and be missing Andy Dawes and Andy Sutton. If I pass the term "Andy Su" it will display Andy Sutton as expected.

Can anyone shed any light on why this is happening?

网友答案:

Try moving the Take(25)

var model =
    db.RPTINQUIRies
        .Where(t => t.CONNAME.StartsWith(term))
        .Select(t => new
        {
            label = t.CONNAME
        })
        .Distinct()
        .Take(25); // Move it HERE!

You want 25 distinct names, not the distinct of the first 25 names that SQL finds in the db :-)

To make it clear: let's say that you have a Take(2):

Your query for all the rows of the db...

Andy Smith
Andy Smith
Andy Bloggs
Andy Dawes

Then you Take(2)...

Andy Smith
Andy Smith

And apply Distinct()...

Andy Smith

But in truth you wanted:

Take all the rows of the db

Andy Smith
Andy Smith
Andy Bloggs
Andy Dawes

Apply Distinct()

Andy Smith
Andy Bloggs
Andy Dawes

Then Take(2)

Andy Smith
Andy Bloggs
分享给朋友:
您可能感兴趣的文章:
随机阅读: