简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM