0

This LINQ query works :

var randomCustomer = db.Customer.OrderBy(c => Guid.NewGuid()).FirstOrDefault();

But when I try to get a random customer with a certain name as below :

var randomCustomer = db.Customer.Where(x => x.Name.Contains(nameid)).OrderBy(c => Guid.NewGuid()).FirstOrDefault();

It doesn't work. How can I get random customer with a certain name? Thanks.

Fabiano
  • 5,124
  • 6
  • 42
  • 69
jason
  • 6,962
  • 36
  • 117
  • 198
  • "It doesn't work?" - what does it mean? Does it throw exception? If not, then what results do you get? And what results do you expect? – Yeldar Kurmangaliyev May 02 '17 at 03:37
  • @YeldarKurmangaliyev it returns null – jason May 02 '17 at 03:38
  • `FirstOrDefault` returns the first element in your collection, or returns null if collection is empty. If it returns null, then it means that there were no elements which match your condition. If you do `db.Customer.Where(x => x.Name.Contains(nameid)).ToArray()`, you should get an empty array. – Yeldar Kurmangaliyev May 02 '17 at 03:39
  • @YeldarKurmangaliyev it returns 330 elements – jason May 02 '17 at 03:41
  • 1
    Ah, I see. It is an IQueryable and you work with database. Then try to make `.ToArray()` before sorting, so that it queries and then sorts objects in-memory: `var randomCustomer = db.Customer.Where(x => x.Name.Contains(nameid)).ToArray().OrderBy(c => Guid.NewGuid()).FirstOrDefault();`. Note that in general selecting all items and sorting it on consumer side is not very performant. – Yeldar Kurmangaliyev May 02 '17 at 03:46
  • http://stackoverflow.com/a/648247/5621827 may help – jitender May 02 '17 at 06:02

0 Answers0