使用linq语句随机选择数据行

时间:2015-07-14 06:33:19

标签: c# linq entity-framework linq-to-entities

在那里,我有一个名为word table的表。包含以下字段: WordID,Word,提示,类别。该表有40行数据。我想随机选择符合特定条件的一行数据。 继承我的代码:

public List<WordTable> get(string diff, string cat)
{
    using(Entities obj = new Entities())
    {
        var qry = (from c in obj.WordTables where c.DifficultyLevel == diff 
                                                  && c.Category == cat select c);
        return qry.ToList();
    }    
}

1 个答案:

答案 0 :(得分:1)

随机选择你可以这样做,

public WordTable get(string diff, string cat)
{
    var qry = (from c in obj.WordTables where 
         c.DifficultyLevel == diff && c.Category == cat select c);
    var list = qry.ToList();
    Random r = new Random()
    var element = list [ r.Next(0, list.count-1)];
    return element;
}