【问题标题】:In a list of objects X , delete all the objects with property T different than the values present in another list of integers?在对象列表 X 中,删除所有具有与另一个整数列表中存在的值不同的属性 T 的对象?
【发布时间】:2018-02-09 14:20:41
【问题描述】:

我有一个整数列表:

List<int> intList = new List<int>();
intList.Add(23);
intList.Add(53);
intList.Add(98);

我有一个 Employee 对象列表:

List<Employee> employeeList = new List<Employee>();
employeeList.Add(m1);
employeeList.Add(m2);
employeeList.Add(m3);
employeeList.Add(m4);
employeeList.Add(m5);
employeeList.Add(m6);
employeeList.Add(m7);

Employee 类型的每个对象都有 3 个属性:

int Age;
string Name;
string Gender;

现在,我有包含 3 个项目的列表 intList,包含 7 个对象的列表 employeeList。 从employeeList 列表中,我想完全删除所有具有Age 属性的Employee 与列表intList 中存在的任何值都不同。

如何以有效的方式做到这一点?

例如,如果m4.Age=2"m6.Age=98 以及所有其他员工的年龄不同, 在阐述结束时,我希望我的employeeList 在位置0 和1 中只包含m4m6

谁能帮我解决这个问题?

【问题讨论】:

  • 为什么你的整数是字符串?
  • @GolezTrol 可能是因为Employee.Age 也是string?当然,这也是值得怀疑的。
  • List&lt;int&gt; intList = new List&lt;string&gt;(); 甚至无法编译。
  • 不,你没有整数列表,因为我认为你做不到List&lt;int&gt; intList = new List&lt;string&gt;();
  • employeeList.RemoveAll(e =&gt; !intList.Contains(e.Age))

标签: c# list iterator


【解决方案1】:

你可以这样做:

employeeList = employeeList.Where(c => intList.Contains(c.Age)).ToList();

【讨论】:

    【解决方案2】:

    或者如果性能是一个问题,你可以稍微不同地存储你的整数:

    Dictionary<int, bool> intMap = new Dictionary<int, bool>();
    intMap.Add(23, true);
    intMap.Add(53, true);
    intMap.Add(98, true);
    

    现在你可以这样做了:

    employeeList = employeeList.Where(c => !intMap.ContainsKey(c.Age))).ToList();
    

    字典键查找将优于列表搜索。

    【讨论】:

      猜你喜欢
      • 2015-07-23
      • 2020-06-09
      • 1970-01-01
      • 1970-01-01
      • 2011-10-22
      • 2019-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多