How to get distinct field list from datatable?

Alick Wang 266 Reputation points
2023-05-19T14:22:03.3466667+00:00

A datatable as follow:

devID kk vv

t1 11 22

t1 22 22

t2 11 66

t3 88 99

t3 33 33

....................................

I want get a list or datarow[] like below:

["t1","t2","t3"]

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,640 questions
{count} votes

Accepted answer
  1. Viorel 114.7K Reputation points
    2023-05-19T15:33:19.88+00:00

    For the new situation, try a code like this:

    . . .
    var results = new DataTable( );
    results.Columns.Add( "devID", typeof( string ) );
    results.Columns.Add( "devName", typeof( string ) );
    
    dt.Rows
        .Cast<DataRow>( )
        .Select( r => new { devID = r.Field<string>( "devID" ), devName = r.Field<string>( "devName" ) } )
        .Distinct( )
        .All( t => { results.Rows.Add( t.devID, t.devName ); return true; } );
    
    1 person found this answer helpful.
    0 comments No comments

3 additional answers

Sort by: Most helpful
  1. Viorel 114.7K Reputation points
    2023-05-19T14:54:41.13+00:00

    Check an example:

    var dt = new DataTable( );
    dt.Columns.Add( "devID", typeof( string ) );
    dt.Columns.Add( "kk", typeof( int ) );
    dt.Columns.Add( "vv", typeof( int ) );
    
    dt.Rows.Add( "t1", 11, 22 );
    dt.Rows.Add( "t1", 11, 22 );
    dt.Rows.Add( "t1", 22, 22 );
    dt.Rows.Add( "t2", 11, 66 );
    dt.Rows.Add( "t3", 88, 99 );
    dt.Rows.Add( "t3", 33, 33 );
    
    string[] result = dt.Rows
                        .Cast<DataRow>( )
                        .Select( r => r.Field<string>( "devID" ) )
                        .Distinct( )
                        .ToArray( );
    
    0 comments No comments

  2. Alick Wang 266 Reputation points
    2023-05-19T15:13:06.7166667+00:00

    devID devName kk vv

    t1 mmm 11 22

    t1 mmm 22 22

    t2 nnn 55 66

    t3 aaaa 88 99

    t3 aaaa 33 33

    ==>

    [{devID="T1",devName="mmm"},

    {devID="T2",devName="nnn"},

    {devID="T3",devName="mmm"},

    ]

    For this situtation? Thanks.

    0 comments No comments

  3. Mansour_Dalir 1,716 Reputation points
    2023-05-20T12:37:02.7733333+00:00

    'I used this in vb.net.

     Dim drSelect() As DataRow = dtMain.Select()
     Dim drGroup = drSelect.GroupBy(Function(row) row(columName))
     Dim arrGroup = drGroup.ToArray
    
    0 comments No comments