Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a Distinct on 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 should be unique. I can't have duplicate items in the ip field. is it possible to do this in linq

like image 569
Luke101 Avatar asked Oct 12 '09 20:10

Luke101


2 Answers

You can achieve what you want by grouping by the ip address, but then you'll need to know how you want to handle the other fields when you do 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()
                     };
like image 73
tvanfosson Avatar answered Nov 05 '22 01:11

tvanfosson


You can only perform a Distinct on all the fields you select, not just on one field (which values would you take for other fields ?).

You can achieve that by using the Distinct extension method :

        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();
like image 35
Thomas Levesque Avatar answered Nov 05 '22 03:11

Thomas Levesque