简体   繁体   中英

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

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?

Logically this kind of approach may not be correct. For example in your record set the second and third row can be distinctly filtered to one row based on the Sid, table and userid. However, If you want to access all fields on a distinct query, the result will be either of the rows which may result in par3 to have different value based on the row returned.

Sid Table userid par1 par2 par3
232 tbl1  43     1    2    0
232 tbl1  43     1    2    1

If you have decided to get all the fields of the first row of each group regardless, then use the following code

var distinct2 = (from t in InYourDatabaseRows
group t by new { t.Sid, t.Table, t.userid }
into grp
select new { 
Sid = grp.Key.Sid,
Table = grp.Key.Table,
userid =grp.Key.userid,
par1 = grp.First().par1,
par2 = grp.First().par2,
par3 = grp.First().par3
}).ToList();    

If I understood correctly your example, what you need is described with the following algorithm:

  • group the rows by Sid , Table and userid
  • return the first row from the group

To do that you can use the following code:

var distinct = Datatable.Rows.Cast<DataRow>()
    .GroupBy(r => new
    {
        Sid = r.Field<int>("Sid"), 
        userid = r.Field<int>("userid"), 
        Table = r.Field<string>("Table")
    })
    .Select(g => g.First())

The code above will return a collection of DataRow objects with their original data and structure as they were in the Datatable . You can bind the rows to any grid without risking to encounter errors about missing members.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM