0

Possible Duplicate:
Random row from Linq to Sql

I'm a total newbie when it comes to .NET. I have this line of code, that pulls the record from the DB containing a specified system name. I have the possibility of naming more than one topic with the same system name.

What I'm hoping for is a way to randomly choose a topic if more than one contains that system name. If only one exists this would be shown as it is now. The code that works to pull the topic with a specified systemname looks like this:

public virtual Topic GetTopicBySystemName(string systemName){
  if (String.IsNullOrEmpty(systemName)) return null;
  var query = from t in _topicRepository.Table
    where t.SystemName == systemName
  select t;
  return query.FirstOrDefault();
}

What do I need to change to achieve the above?

Community
  • 1
  • 1

1 Answers1

0

Not at a machine that I can test, but:

Random random = new Random();
int count = query.Count();
if(count <= 1) return query.FirstOrDefault();
return query.Skip(random.Next(0, count)).First();
naspinski
  • 34,020
  • 36
  • 111
  • 167