Search code examples
c#asp.netvb.netarraylistrepeater

Select distinct items with a specific field in an array and display in tabular form


I have a stored procedure which is returning 3 columns/fields and i'm saving the result set in an arrayList. Each row contains three fields ID,name,description.I want to get all distinct category from this array into separate array or some other objects.

For example, if my output had 100 rows returned by sproc, there might be 10 rows with category1, 20 rows with category2, 35 rows with category3 and so.

Now i need to display like below, i.e display all ID comes under each category.

category1
ID Name
1  A
19 B
32 C

category2
ID Name

10  D
11  T
54  D

and so on...

I can use gridview or Repeater or table to display this.

Sample code:

 Dim a As ArrayList
 a = //values from sproc
 'we need to implement some logic here display like above.

Please let me know how to display this properly. Thanks in advance!


Solution

  • Some nested linq queries should get you that result...I've put together an example of the principle, but of course it will need to be adapted to your program (can't tell what language you're using from your tags/post, so this is in vb.net):

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim lstAry As New List(Of String())
        lstAry.Add({"1", "a", "d1"})
        lstAry.Add({"1", "b", "d3"})
        lstAry.Add({"2", "c", "d2"})
        lstAry.Add({"3", "a", "d4"})
        lstAry.Add({"3", "a", "d5"})
    
        Dim distinctCats = lstAry.Select(Function(x) x(0)).Distinct
        If distinctCats IsNot Nothing Then
            For Each distinctcat As String In distinctCats
                Debug.Print("") 
                Debug.Print(distinctcat)
                Dim catmembers = lstAry.Where(Function(x) (x(0) = distinctcat)).Distinct
                If catmembers IsNot Nothing Then
                    For Each catmember As String() In catmembers
                        Debug.Print(catmember(1) & "   " & catmember(2))
                    Next
                End If
            Next
        End If
    End Sub
    

    This outputs:

    1
    a   d1
    b   d3
    
    2
    c   d2
    
    3
    a   d4
    a   d5
    

    So if you run this sub's logic on your array list you should get results formatted pretty closely to what you're looking for. First I'm getting the distinct categories, and then getting the distinct arrays for each category and just printing each group.