1

I need to fetch an entity randomly as showed below, but ElementAtAsync does not exist. What is the reason for this and what can be a workaround?

var index = random.Next(maxValue:count);
var song = await Context.Songs.ElementAt(index);
keenthinker
  • 7,645
  • 2
  • 35
  • 45
Freshblood
  • 6,285
  • 10
  • 59
  • 96
  • ElementAtAsync does not exist for the same reasons that any other language/framework does not exist. The benefit did not outweigh the cost. – Robert Harvey May 03 '14 at 17:08
  • On reflection, how much time could ElementAt possibly take? Microsoft's guideline is that if it takes 50ms or less to execute, then it doesn't have to be made asynchronous. – Robert Harvey May 03 '14 at 17:45

2 Answers2

2

If you only need one element from the db, and you already have the count, you can do something like this:

var index = random.Next(maxValue:count);
var songQuery = await Context.Songs
                             .OrderyBy(x => x.Something) 
                             .Skip(index)
                             .Take(1)
                             .ToListAsync();
var song = songQuery.SingleOrDefault(); // this works due to the Take(1) above
Christopher Stevenson
  • 2,843
  • 20
  • 25
0

I am not sure why it is not exist but a workaround can be like below.

var song await = Context.Songs.OrderBy(o => o.Id)
                        .Skip(index)
                        .FirstOrDefaultAsync();

This Linq query will cause same result but underlying query can be bit of different.

Freshblood
  • 6,285
  • 10
  • 59
  • 96
  • Probably your last sentence. – Robert Harvey May 03 '14 at 17:09
  • @RobertHarvey I mean that i am not sure that it exactly execute same sql query as ElementAt does. This linq query will exactly cause same result if it is even not exactly same sql query with ElementAt. – Freshblood May 03 '14 at 17:13
  • I down voted it since I didn't like idea of you taking the knowledge/idea of @ChristoperStevenson and because of a small mistake in his answer, you answer your own question. Thats why I up voted Christopher's answer and down voted yours, if you accepted your own answer instead of Christopher's I would be even more disappointed. – Rand Random May 03 '14 at 23:17