C# 使用 LINQ 将 ID 列表与对象列表中的每个 ID 进行比较

标签 c# linq

我正在尝试将整数列表与对象列表进行比较。查看其中一个 ID 是否与每个对象中的 a 键匹配。如果是,则返回 true,否则返回 false。

例如:

List<int> ints = new List<int> () { 
  1, 2, 3, 4, 5};

List<someObjectType> objects = new List<someObjectType> () { 
  {1, "one"}, {6, "six"}, {45, "forty-five"} };

(x => x.objects.any(a => ints.contains(x.id)));

但是我不知道如何将一个整数列表与一个对象的一个​​属性进行比较,我只知道如何将整个数组相互比较。

最佳答案

你在找这样的东西吗?

  List<int> ints = new List<int> () { 1, 2, 3, 4, 5};

  // For better performance when "ints" is long
  HashSet<int> ids = new HashSet<int>(ints);

  List<someObjectType> objects = new List<someObjectType> () { 
    {1, "one"}, {6, "six"}, {45, "forty-five"} };

  // if any is matched?
  boolean any = objects
    .Any(item => ids.Contains(item.id));

  // All that match
  var objectsThatMatch = objects
    .Where(item => ids.Contains(item.id));

关于C# 使用 LINQ 将 ID 列表与对象列表中的每个 ID 进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29971401/

相关文章:

c# - 将单独的 XAML 导入为 ResourceDictionary 并分配 x :Key

c# - async/await 创建新线程,输出窗口显示

c# - 在 C# 中计算大写字符数的最快方法

c# - 用 Epplus 寻找值(value)

c# - Linq 求和和 null

c# - 多对多父子转发器,数据关系c#

c# - 应该在哪里订阅 AppDomain.UnhandledException?

c# - 如何删除没有子类别的类别

c# - LINQ 查询在不可为 null 的字段上返回 null

c# - 使用 System.Linq.Dynamic 自定义排序顺序