从对象列表中删除特定项目

时间:2017-03-13 08:54:58

标签: c# .net linq

我有对象列表:

public class SDesc
{
    public string sensorId { get; set; }
    public string address { get; set; }
}

List<SDesc> desc = new List<SDesc>
{
    new SDesc {sensorId = "1234", address =   "Adams22"},
    new SDesc {sensorId = "5555", address =   "Hourton34"},
    new SDesc {sensorId = "4444", address =   "SaintsRoad55"},
    new SDesc {sensorId = "1258", address =   "BerryAve58"},
    new SDesc {sensorId = "52486", address =   "SaintsRoad2"},
    new SDesc {sensorId = "12361", address =   "TomassonRoad"}
}

我也有IEnumarable字符串:

IEnumarable<string> sId = {"4444","52486","12361"};

来自 desc 列表我需要删除sId列表中sensorId属性存在的记录。

例如,对于上述情况,我想得到的结果是:

List<SDesc> desc = new List<SDesc>
{
    new SDesc {sensorId = "1234", address =   "Adams22"},
    new SDesc {sensorId = "5555", address =   "Hourton34"},
    new SDesc {sensorId = "1258", address =   "BerryAve58"},
}

这是我试过的:

desc.RemoveAll(obj => obj.sensorId == sId);

但它不能正常工作,因为sID是IEnumarable类型。

所以我的问题是如何从 desc 列表中移除物品,其中sensorsId属性存在于sId列表中?

2 个答案:

答案 0 :(得分:3)

您需要使用Any,例如:

 desc.RemoveAll(obj => sId.Any(x=> x== obj.sensorId ));

正如方法名称建议的那样,它会检查sId中的任何项目是否与descsensorId的项目相匹配,它会从List<T>中移除这些项目。

答案 1 :(得分:2)

您可以使用.Contains() LINQ方法检查集合是否包含项目:

desc.RemoveAll(obj => sId.Contains(obj.sensorId));

但是,它会导致枚举sId的多次枚举。在这种情况下,这不是问题,因为这个可枚举的数组是,在这种特殊情况下

详细了解“可能的多重枚举”:
- Handling warning for possible multiple enumeration of IEnumerable
- Resharper's example code for explaining "Possible multiple enumeration of IEnumerable"

我建议将其转换为一个集合,以确保只列举一次IEnumerable 正如Evk在评论中所建议的那样,最好使用HashSet以便.ContainsO(1)时间内执行:

List<SDesc> desc = new List<SDesc> {
  new SDesc {sensorId = "1234", address =   "Adams22"},
  new SDesc {sensorId = "5555", address =   "Hourton34"},
  new SDesc {sensorId = "4444", address =   "SaintsRoad55"},
  new SDesc {sensorId = "1258", address =   "BerryAve58"},
  new SDesc {sensorId = "52486", address =   "SaintsRoad2"},
  new SDesc {sensorId = "12361", address =   "TomassonRoad"}
};

IEnumarable<string> sId = {"4444","52486","12361"};
var sIdsSet = new HashSet(sId);

desc.RemoveAll(obj => sIdsSet.Contains(obj.sensorId));