简体   繁体   English

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

[英]C# compare a list of IDs to each ID in a list of objects using LINQ

I'm attempting to compare list of ints to a list of objects. 我正在尝试将整数列表与对象列表进行比较。 to see if one of the IDs match the a key in each object. 查看其中一个ID是否与每个对象中的a键匹配。 If it does then return true, else false. 如果是,则返回true,否则返回false。

for example: 例如:

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)));

However I don't know how to compare a list of ints to only one property on an object, I only know how to compare whole arrays to each other. 但是我不知道如何将一个整数列表与一个对象的一个​​属性进行比较,我只知道如何将整个数组进行比较。

Are you looking for something like that? 您是否正在寻找类似的东西?

  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));

Your pseudo-code is pretty much there (though with Where instead of Any )... 您的伪代码几乎在那里(尽管使用Where而不是Any )...

var objectsWithIds = objects.Where(o => ints.Contains(o.Id));

Which makes me suspect this isn't what you are after... 这让我怀疑这不是你所追求的...

Another way is using Intersect , but you need to translate them both into an IEnumerable<> of the same type. 另一种方法是使用Intersect ,但是您需要将它们都转换为相同类型的IEnumerable<>

var intersectionOfIds = objects.Select(_ => _.Id).Intersect(ints);

But this only gets you a list of Ids that are in both lists, not the objects themselves, which you would then need to go and find again. 但是,这只会为您提供两个列表中都包含的Id列表,而不是对象本身,然后需要再次查找它们。

Instead of object , you could use the keyword dynamic , but an even better solution would be to use some static type (if possible). 可以使用关键字dynamic代替object ,但是更好的解决方案是使用某种静态类型(如果可能)。

You can use dynamic like a dictionary, the added link will provide you with some great examples. 您可以像字典一样使用dynamic ,添加的链接将为您提供一些出色的示例。

我离得很近

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM