Reputation: 2851
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:
ID nType nAmount
1 A 12.00
2 A
3 B 13.00
4 C 14.00
Upvotes: 0
Views: 189
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
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
nType
which has a null nAmount
it will not appear in the resultsnType
with a non-null nAmount
this will take the first one.Upvotes: 1