Search code examples
c#linqlinq-group

how to group by one column only using linq?


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();

Solution

  • 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()
                        };