You must Sign In to post a response.
  • Category: LINQ

    Fetch distinct record from datatable using linq to datatable and shows all columns of data

    I am fetching record from database and store a result in dataset.

    My dataset like this

    Sid Table userid par1 par2 par3
    274 tbl1 43 0 0 0
    232 tbl1 43 1 2 0
    232 tbl1 43 1 2 1
    232 tbl2 43 1 2 0
    232 tbl2 43 1 2 1
    I want to show all 6 column but distinct record.Distinct should be on Sid, Table and userid.I want output like this

    Sid Table userid par1 par2 par3
    274 tbl1 43 0 0 0
    232 tbl1 43 1 2 0
    232 tbl2 43 1 2 0
    So Used following query.I am new to linq.

    Datatable.Rows.Cast<DataRow>()
    .GroupBy(r => new { Sid = r.Field<int>("Sid"), userid = r.Field<int>("userid"), Table = r.Field<string>("Table") })
    .Select(e => e.FirstOrDefault())
    .Select(grp => new
    {
    Sid = grp.Field<int>("Sid"),
    userid = grp.Field<int>("userid"),
    Table = grp.Field<string>("Table"),
    par1 = grp.Field<int>("par1"),
    par2 = grp.Field<int>("par2"),
    par3 = grp.Field<int>("par3")
    });
    My columns are dynamic in nature.some user have par2,some 1 like that.Is there any way to select all column instead of specifying column names?
  • #764982
    Hi

    We can't group this because columns data different different so we cant do group query.

    Name : Dotnet Developer-2015
    Email Id : kumaraspcode2009@gmail.com

    'Not by might nor by power, but by my Spirit,' says the LORD Almighty.

  • #764987
    Why can not you try "Distinct()" in your linq query?

    Datatable.Rows.Cast<DataRow>()
    .GroupBy(r => new { Sid = r.Field<int>("Sid"), userid = r.Field<int>("userid"), Table = r.Field<string>("Table") })
    .Select(e => e.FirstOrDefault())
    .Select(grp => new
    {
    Sid = grp.Field<int>("Sid"),
    userid = grp.Field<int>("userid"),
    Table = grp.Field<string>("Table"),
    par1 = grp.Field<int>("par1"),
    par2 = grp.Field<int>("par2"),
    par3 = grp.Field<int>("par3")
    })
    .Distinct();

    By Nathan
    Direction is important than speed

  • #765010
    Hi,

    Using Distinct method you can able to get the unique records using LINQ query, refer below link this might be helpful to you "stackoverflow.com/questions/3242892/select-distinct-rows-from-datatable-in-linq"

    --------------------------------------------------------------------------------
    Give respect to your work, Instead of trying to impress your boss.

    N@veen
    Blog : http://naveens-dotnet.blogspot.in/


  • Sign In to post your comments