Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ GroupBy except null values

Tags:

c#

linq

group-by

My aim is to list out duplicates, here's what I'm trying:

var duplicates = result
                 .GroupBy(x => x.col1)
                 .SelectMany(y => y.Count() > 1 ? y.Where(z => z.col2== decimal.Zero) : y)
                 .AsEnumerable()
                 .ToList();

but it's been grouped by all null values in col1.

Sample input

| col1   | col2   |
|--------|--------|
| 1/1/21 | 0.00   |
| 2/1/21 | 120.00 |
| 2/1/21 | 0.00   |
| 3/1/21 | 110.00 |
| null   | 140.00 |
| null   | 220.00 |
| 6/1/21 | 0.00   |
| 6/1/21 | 0.00   |
| 7/1/21 | 0.00   |
| null   | 0.00   |
|--------|--------|

Desired output

| col1   | col2   |
|--------|--------|
| 1/1/21 | 0.00   |
| 2/1/21 | 120.00 |
| 3/1/21 | 110.00 |
| null   | 140.00 |
| null   | 220.00 |
| 6/1/21 | 0.00   |
| 7/1/21 | 0.00   |
| null   | 0.00   |
|--------|--------|
like image 287
MK88 Avatar asked Nov 02 '25 16:11

MK88


2 Answers

In your GroupBy(), you need to handle the case where col1 is null and assign a unique value for the group key. A Guid would do the job well. Try this:

var duplicates = result
                 .GroupBy(x => x.col1 == null ? Guid.NewGuid().ToString() : x.col1)
                 .Select(x => x.First())
                 .ToList();
like image 93
Connell.O'Donnell Avatar answered Nov 04 '25 08:11

Connell.O'Donnell


For selecting duplicates this query should work:

var duplicates = result
   .GroupBy(x => x.col1)
   .Where(y => y.Count() > 1)
   .SelectMany()
   .ToList();
like image 44
Svyatoslav Danyliv Avatar answered Nov 04 '25 07:11

Svyatoslav Danyliv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!