views:

857

answers:

3

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

A: 

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();
Thomas Levesque
+1  A: 

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()
                     };
tvanfosson
this worked great. Thanks
Luke101
A: 

You can also use Distinct() with an equality comparer (ie, pass in a method that will compare the IP value, and ignore the rest). But as tvanfosson asks, what is the correct procedure for handling duplicate values?

Nader Shirazie