VB LINQ - 从每个组中随机抽取一行

时间:2015-06-17 18:15:15

标签: vb.net linq random

我正试图从每组行中获取一个随机行。我正在尝试使用LINQ,但我不确定这是否是正确的方法。我想要一个键/名字对词典。

我的表是这样的:

AnswerGroup     AnswerKey   AnswerName
---------------------------------------------
1               1           Yes
1               2           No
2               1           Never
2               2           A little bit
2               3           Mostly
2               4           Always
3               1           White
3               2           African American
3               3           Hispanic
3               4           Asian or Pacific Islander

对于每个AnswerGroup,我需要选择一个随机的Key / Name对。

我有一个LINQ查询的开头,但坦率地说,我失去了因为我不理解LINQ分组以及如何向该组添加Enumerable.Take(1)。

    Dim answerGroup As String = "AnswerGroup"
    Dim answerKey As String = "AnswerKey"
    Dim answerName As String = "AnswerName"

    Dim query = _
        From rows As DataRow In surveyAnswerKeys.Rows _
        Order By rows(answerGroup) _
        Group By questionSortKey = rows(answerGroup) _
        Into questionGroups = Group 

任何帮助将不胜感激。谢谢!

编辑: 我可以在调试器中展开以下查询,以查看生成一系列DataRows的内存查询。当我将鼠标悬停在questionGroups上时,它表示它是一个IEnumerable(Of Object)。当我尝试将该查询运行到列表或DataTable时,我收到错误:

  

“公共成员'ToTable'类型'WhereSelectEnumerableIterator(Of   VB $ AnonymousType_0(Of Object,IEnumerable(Of Object)),Object)'不是   找到。“

    Dim answerGroup As String = "QuestionSortKey"
    Dim answerNo As String = "AnswerNo"
    Dim surveyDefinitionNo As String = "Pk_SurveyDefinitionNo"

    Dim query = _
        From rows In surveyAnswerKeys.Rows _
        Where rows(answerNo) IsNot Nothing _
        Order By Guid.NewGuid() _
        Group By questionSortKey = rows(answerGroup) _
        Into questionGroups = Group _
        Select questionGroups.First()

    Dim randomAnswerNos As DataTable = query.ToTable

2 个答案:

答案 0 :(得分:1)

一种快速移动项目的方法是按“随机”值排序 - Guid.NewGuid()通常效果很好。然后从每组中拉出第一行:

Dim query = _
    From rows As DataRow In surveyAnswerKeys.Rows _
    Order By Guid.NewGuid() _
    Group By questionSortKey = rows(answerGroup) _
    Into questionGroups = Group _
    Select questionGroups.First() 

答案 1 :(得分:-2)

Linq不能用于拉随机行。我建议你将所有行存储在一个表中,并手动循环遍历每个组。然后根据每个组中的行数生成一个随机数并选择该行。仅使用LINQ进行查询并检索结果。