USe LINQ to remove from a list based on conditions

2019-08-26 06:56发布

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

2条回答
Explosion°爆炸
2楼-- · 2019-08-26 07:43

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.
查看更多
Melony?
3楼-- · 2019-08-26 07:50
var result = nList.Where(x => x.nAmount != null).DistinctBy(x => x.nType);

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

查看更多
登录 后发表回答