1

I am using a Linq query to group a column (string of Phones) and return that column and the last value of a second column called Status (also a string of numbers). I want to add the result of this query to a new dataTable.

I've tried it in many ways, but the result is always a group of the two columns together and not by one only. If I remove the field status from the dataTable then the group works good, but I need it. Example:

phone status

123 --------- 1

123 --------- 2

I want to retrieve the result: 123, 2 but I get the two rows. Any idea why something like that might happen? This is the code:

var queryGroupLog =
from log2 in lg2.AsEnumerable()
group log2 by log2.Field<string>("Phone") into groupPhone
select groupPhone.OrderBy(p => p.Field<string>("Status")).LastOrDefault();
ekad
  • 14,436
  • 26
  • 44
  • 46
Talkat
  • 13
  • 4

2 Answers2

2

You could try something like this:

var queryGroupLog = from log2 in lg2.AsEnumerable()
                    group log2 by log2.Field<string>("Phone") into groupPhone
                    select new 
                    {
                        Phone = groupPhone.Key,
                        Status = groupPhone.OrderBy(p => p.Field<string>("Status"))
                                           .LastOrDefault()
                    };
Christos
  • 53,228
  • 8
  • 76
  • 108
  • is this equals `groupPhone.Max(...)`? – Grundy Aug 02 '15 at 08:41
  • @Grundy I think it's the same. However, I haven't tested it. – Christos Aug 02 '15 at 08:43
  • Thanks, but I'm afraid I'm getting the same result. I'm the checking the result in two ways: 1. foreach (var row in queryGroupLog) { log_grouped.Rows.Add(row); } Console.WriteLine("{0}", log_grouped.Rows.Count); ---------------------------------------------------------------------------------- 2. foreach (var nameGroup in queryGroupLog) {Console.WriteLine("{0}", b); b++; } ----------------------------------------------------------------------I'm getting the number of a result of a group by both columns. – Talkat Aug 02 '15 at 10:37
  • Found the problem! and used the answer above also. Thanks again! :) – Talkat Aug 02 '15 at 15:12
-1
new KeyValuePair(groupPhone.Key,groupPhone.OrderBy((p) => p.Field("Status")).LastOrDefault()))
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Thaina Yu
  • 1,372
  • 2
  • 16
  • 27