DarkW1nter
DarkW1nter

Reputation: 2851

USe LINQ to remove from a list based on conditions

I have a list 'nList' returned from a LINQ query. The data is correct but I have to check if the data in the 2nd field ('nType') occurs more than once, and if it does, remove it from the list if the 3rd field ('nAmount') is null. To illustrate, in the example below, I would want to remove the record with ID 2. Can this be done using LINQ?

EDIT: There can only be 2 scenarios:

  1. one occurrence of nType, with nAmount populated
  2. two occurences of nType, with one nAmount populated, the other nAmount null

ID  nType     nAmount
1   A         12.00
2   A          
3   B         13.00
4   C         14.00

Upvotes: 0

Views: 189

Answers (2)

pitersmx
pitersmx

Reputation: 957

var result = nList.Where(x => x.nAmount != null).DistinctBy(x => x.nType);

You would need to install MoreLinq from Nuget to get the DistinctBy().

Upvotes: 2

Jamiec
Jamiec

Reputation: 136104

This can be done with a GroupBy overload which lets you define the grouped object

var result = nList.GroupBy(
                   x => x.nType, 
                   (key,g) => new { 
                       ID = g.First(x => x.nAmount != null).ID, 
                       nType = key, 
                       nAmount = g.First(x => x.nAmount != null).nAmount }
             );

Live example: http://rextester.com/PFX41986

This has a few caveats

  • If your resultset has a single nType which has a null nAmount it will not appear in the results
  • If you get more than 1 distinct nType with a non-null nAmount this will take the first one.

Upvotes: 1

Related Questions