2

Trying to return a distinct list of SubString in LINQ.

This is returning the list but there are 100 records with the substring. I only want to return the distinct list.

var query = from b in db.Certificates
            select b.CertificateNumber.Substring(0,4);

ViewBag.BoxNumber = new SelectList(query.ToList());

I tried adding the distinct as in

select b.CertificateNumber.Substring(0,4).Distinct();

But it threw

DbDistinctExpression requires a collection argument.

3 Answers 3

6

The way you're currently doing it, it's going to attempt to do a Distinct on the first four characters of each certificate number (stripping out duplicate characters), then return all of the results. You're probably getting the error because the driver you're using is unable to create a valid SQL query that way.

Instead, surround the entire first part of the query in parentheses before calling Distinct, like this:

var query = (from b in db.Certificates
             select b.CertificateNumber.Substring(0,4)).Distinct();

Alternatively, using method syntax instead of a mixture of query and method syntax:

var query = db.Certificates
              .Select(cer => cer.CertificateNumber.Substring(0,4))
              .Distinct();
Sign up to request clarification or add additional context in comments.

4 Comments

How would I order by the resulting list?
Thank You! Gonna ask a new question on updating using that value, don't want to do it here, might get yelled at.
How would I add a where clause to this where Active='Y'
1

I got it

ViewBag.BoxNumber = new SelectList(query.ToList().Distinct());

2 Comments

stackoverflow.com/questions/17401772/… look at this comparison and take my advice running distinct, then tolist
I don't think you got it. If you had got it, you would've chosen Grant's answer as the right answer. Because, his answer does the same thing in a nicer way.
1
 var certificatesList = (from b in db.Certificates
                    select b.CertificateNumber.Substring(0,4)).Distinct().ToList();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.