使用LINQ根据条件从列表中删除 [英] USe LINQ to remove from a list based on conditions

查看:173
本文介绍了使用LINQ根据条件从列表中删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从LINQ查询返回的列表'nList'.数据是正确的,但我必须检查第二个字段(nType)中的数据是否出现多次,如果确实出现,则如果第三个字段(nAmount)为空,则将其从列表中删除. 为了说明这一点,在下面的示例中,我想删除ID为2的记录. 可以使用LINQ做到吗?

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?

只能有2种情况:

  1. 一次出现nType,填充了nAmount
  2. 两次出现nType,填充一个nAmount,另一个nAmount为空


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

推荐答案

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

您需要从Nuget安装MoreLinq以获得DistinctBy().

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

这篇关于使用LINQ根据条件从列表中删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆