How to use Distinct in a column using Linq

Here is my code:

var query = from row1 in table.AsEnumerable()
                         let time = row1.Field<DateTime>("time")
                         let uri = row1.Field<string>("cs-uri-stem")
                         let ip = row1.Field<string>("c-ip")
                         let questionid = row1.Field<int>("questionid")
                         where questionid == int.Parse(table.Rows[x]["questionid"].ToString())
                         select new
                         {
                             time,
                             uri,
                             ip,
                             questionid
                         };

The ip column must be unique. I cannot duplicate elements in ip field. is it possible to do this in linq

+5
source share
3 answers

You can achieve what you want by grouping by IP address, but then you need to know how you want to handle other fields when you have duplicates.

var query = from row1 in table.AsEnumerable()
                     let time = row1.Field<DateTime>("time")
                     let uri = row1.Field<string>("cs-uri-stem")
                     let ip = row1.Field<string>("c-ip")
                     let questionid = row1.Field<int>("questionid")
                     where questionid == int.Parse(table.Rows[x]["questionid"].ToString())
                     group by ip into g
                     select new
                     {
                         time = g.time.First(),
                         uri = g.uri.First(),
                         ip = g.Key,
                         questionid = g.questionid.First()
                     };
+7
source

You can only execute Distinctin all fields of your choice, and not just on one field (what values ​​would you take for other fields?).

You can achieve this using the extension method Distinct:

        var query = (from row1 in table.AsEnumerable()
                     let time = row1.Field<DateTime>("time")
                     let uri = row1.Field<string>("cs-uri-stem")
                     let ip = row1.Field<string>("c-ip")
                     let questionid = row1.Field<int>("questionid")
                     where questionid == int.Parse(table.Rows[x]["questionid"].ToString())
                     select new
                     {
                         time,
                         uri,
                         ip,
                         questionid
                     }).Distinct();
+2

Distinct() (.. , IP, ). tvanfosson, ?

+2

All Articles