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.

ataravati
  • 8,891
  • 9
  • 57
  • 89
Doug Farrell
  • 135
  • 1
  • 3
  • 20

3 Answers3

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();
Grant Winney
  • 65,241
  • 13
  • 115
  • 165
1

I got it

ViewBag.BoxNumber = new SelectList(query.ToList().Distinct());
Doug Farrell
  • 135
  • 1
  • 3
  • 20
  • http://stackoverflow.com/questions/17401772/iqueryable-distinct-vs-listt-distinct look at this comparison and take my advice running distinct, then tolist – Razvan Dumitru Jan 15 '15 at 00:58
  • 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. – ataravati Jan 15 '15 at 01:08
1
 var certificatesList = (from b in db.Certificates
                    select b.CertificateNumber.Substring(0,4)).Distinct().ToList();
Razvan Dumitru
  • 11,815
  • 5
  • 34
  • 54